可以使用springboot的监听器来实现获取config配置嘛?

来源:6-7 缓存系统常量数据

黄会长

2021-01-17

图片描述

写回答

1回答

黄会长

提问者

2021-01-17

//img1.sycdn.imooc.com/szimg/6004014d09dbcf8811140846.jpg

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();
    }
}

代码如下

3
1
神思者
可以,但是我觉得反射更简单
2021-01-17
共1条回复

SpringBoot 在线协同办公小程序开发 全栈式项目实战

未来趋势型业务 + 前后端综合技术栈 + 惊艳的细节打磨

1798 学习 · 1915 问题

查看课程