可以使用springboot的监听器来实现获取config配置嘛?
来源:6-7 缓存系统常量数据

黄会长
2021-01-17
写回答
1回答
-
黄会长
提问者
2021-01-17
package com.hhz.emos.common.listener; import cn.hutool.core.util.StrUtil; import com.hhz.emos.pojo.Config; import com.hhz.emos.service.ConfigService; import lombok.extern.slf4j.Slf4j; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.context.event.ApplicationStartedEvent; import org.springframework.context.ApplicationEvent; import org.springframework.context.ApplicationListener; import org.springframework.context.annotation.Configuration; import org.springframework.core.Ordered; import org.springframework.core.annotation.Order; import java.lang.reflect.Field; import java.util.List; /** * 全局监听器,赋值sys_config配置 */ @Slf4j @Configuration @Order(Ordered.HIGHEST_PRECEDENCE) public class ConfigListener implements ApplicationListener<ApplicationStartedEvent> { @Autowired private ConfigService configService; @Autowired private SystemConstants constants; /** * Handle an application event. * @param event the event to respond to */ @Override public void onApplicationEvent(ApplicationStartedEvent event) { List<Config> list = this.getConfigs(); list.forEach(item -> { String paramKey = item.getParamKey(); String paramValue = item.getParamValue(); paramKey = StrUtil.toCamelCase(paramKey); try { Field field = constants.getClass().getField(paramKey); field.set(constants,paramValue); } catch (NoSuchFieldException | IllegalAccessException e) { log.error("获取config配置失败{}",e.getMessage()); e.printStackTrace(); } }); } private List<Config> getConfigs() { return configService.list(); } }
代码如下
312021-01-17
相似问题