spring boot 配置文件优先级调整
适用场景
- 想本地配置覆盖配置中心配置
- 通一个配置存在多个配置文件中顺序调整
实现原理
org.springframework.beans.factory.support.AbstractBeanFactory#addEmbeddedValueResolver最终存储配置方法
org.springframework.beans.factory.support.AbstractBeanFactory#resolveEmbeddedValue根据KEY获取配置方法
在调用addEmbeddedValueResolver之前 中方法前调整配置文件顺序即可
实现方案
工程resources文件夹下新建 META-INF/spring.factories 文件
spring.factories文件内容
org.springframework.context.ApplicationListener=\
com.example.demo.test.MyApplicationListener
自定义监听器代码
public class MyApplicationListener implements ApplicationListener, Ordered { @Override public void onApplicationEvent(ApplicationEvent event) { if (event instanceof ApplicationEnvironmentPreparedEvent) { ConfigurableEnvironment environment = ((ApplicationEnvironmentPreparedEvent) event).getEnvironment(); MutablePropertySources propertySources = environment.getPropertySources(); PropertySource<?> propertySource = propertySources.remove("applicationConfig: [classpath:/application.properties]"); if (propertySource != null) { propertySources.addFirst(propertySource); } } } @Override public int getOrder() { return Ordered.HIGHEST_PRECEDENCE + 19; } }
黄色部分替换成自己需要调整的配置文件名称,可debug自行查看
浙公网安备 33010602011771号