目录
springboot读取外部配置文件

EnvironmentPostProcessor允许在spring application context refreshed之前定制application运行环境,插入自定义的配置信息

1、创建EnvPostProcessor类,继承EnvironmentPostProcessor

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
public class EnvPostProcessor implements EnvironmentPostProcessor {

public static final String FILE_PATH = "/app/project/kbs-nacos-addr/bootstrap.properties";

@Override
public void postProcessEnvironment(ConfigurableEnvironment environment, SpringApplication application) {
try {
File file = new File(FILE_PATH);
if(file.exists()){
InputStream inputStream = new FileInputStream(file);
Properties properties = new Properties();
properties.load(inputStream);
String addr = (String) properties.get("spring.cloud.nacos.config.server-addr");
if (StringUtils.isNotEmpty(addr)) {
MutablePropertySources propertySources = environment.getPropertySources();
OriginTrackedMapPropertySource propertySource = (OriginTrackedMapPropertySource) propertySources
.get("applicationConfig: [classpath:/bootstrap.properties]");
if (propertySource != null) {
Map<String, Object> map = propertySource.getSource();
map.put("spring.cloud.nacos.config.server-addr", addr);
environment.getPropertySources().addLast(propertySource);
}
}
}
} catch (IOException e){
log.error("加载配置文件异常:{}", e.getMessage());
}

}

}

2、创建spring.factories文件,添加以下配置,属性值对应自定类的全类名

1
org.springframework.boot.env.EnvironmentPostProcessor=com.powersi.kbs.config.EnvPostProcessor

3、pom.xml打包时包含spring.factories文件

1
2
3
4
5
6
<resource>
<directory>src/main/resources</directory>
<includes>
<include>**/*.factories</include>
</includes>
</resource>

特别注意:网上教程存在一些误导性,不能直接覆盖掉war包中属性文件,更适合自定义的配置文件。文中所示代码,是取出属性文件对应的对象再进行值替换

文章作者: 微光
文章链接: http://www.guduke.cn/2020/11/29/outSideFile/
版权声明: 本博客所有文章除特别声明外,均采用 CC BY-NC-SA 4.0 许可协议。转载请注明来自 微光
打赏
  • 微信
  • 支付宝

评论