springboot重新获取配置文件参数

springboot重写配置参数要实现 EnvironmentPostProcessor方法

重写springboot中rocketmq.name-server 这个参数,从其他地方获取

因为我们这面有个变量是根据环境来确定的,所以需要重写

@Component
public class MQConfigProperty implements
    EnvironmentPostProcessor {


    private static final String PROPERTY_SOURCE_NAME = "applicationConfig: [classpath:/application.properties]";


    public static final String nameServer = EnvironmentAddress.getConfig(EnvironmentAddress.MQ);

    @Override
    public void postProcessEnvironment(ConfigurableEnvironment environment,
        SpringApplication springApplication) {
        Map map = new HashMap();
        map.put("rocketmq.name-server", this.nameServer);
        addOrReplace(environment.getPropertySources(), map);
    }

    private void addOrReplace(MutablePropertySources propertySources,
        Map map) {
        MapPropertySource target = null;
        if (propertySources.contains(PROPERTY_SOURCE_NAME)) {
            PropertySource source = propertySources.get(PROPERTY_SOURCE_NAME);
            if (source instanceof MapPropertySource) {
                target = (MapPropertySource) source;
                for (String key : map.keySet()) {
                    if (target.containsProperty(key)) {
                        System.out.printf("reload properties key:%s,value:%s \n",key,map.get(key));
                        target.getSource().put(key, map.get(key));
                    }
                }
            }
        }
        if (target == null) {
            target = new MapPropertySource(PROPERTY_SOURCE_NAME, map);
        }
        if (!propertySources.contains(PROPERTY_SOURCE_NAME)) {
            propertySources.addLast(target);
        }
    }
}

编写完这个类需要创建src/main/resources/META-INF/spring.factories

里面填写

org.springframework.boot.env.EnvironmentPostProcessor=
MQConfigProperty

这样的话springboot就可使用最新的值了

你可能感兴趣的:(springboot)