欢迎访问 生活随笔!

生活随笔

当前位置: 首页 > 运维知识 > linux >内容正文

linux

Linux新建yaml文件,Spring Boot 装载自定义yml文件

发布时间:2025/3/15 linux 66 豆豆
生活随笔 收集整理的这篇文章主要介绍了 Linux新建yaml文件,Spring Boot 装载自定义yml文件 小编觉得挺不错的,现在分享给大家,帮大家做个参考.

yml格式的配置文件感觉很人性化,所以想把项目中的.properties都替换成.yml文件,蛋疼的是springboot自1.5以后就把@configurationProperties中的location参数去掉,各种查询之后发现可以用YamlPropertySourceLoader去装载yml文件,上代码

public void onApplicationEvent(ApplicationEnvironmentPreparedEvent event) {

ResourceLoader loader = new DefaultResourceLoader();

YamlPropertySourceLoader yamlLoader = new YamlPropertySourceLoader();

List yamlFilePaths = new ArrayList<>();

while(true){

String yamlFilePath = environment.getProperty("load.yaml["+i+"]");

if(yamlFilePath==null){

break;

}

i++;

if("".equals(yamlFilePath)){

continue;

}

yamlFilePaths.add(yamlFilePath);

}

yamlFilePaths.forEach(filePath->{

try {

environment.getPropertySources().addLast(yamlLoader.load(filePath,loader.getResource(filePath),null));

} catch (IOException e) {

logger.error("load property file failed!file:" + filePath);

throw new RuntimeException(e);

}

});

}

这里主要实现了spring boot的ApplicationListener接口,spring boot为我们提供了四种监听事件:

1.ApplicationStartedEvent                spring boot 刚启动时会触发事件

2.ApplicationEnvironemntPreparedEvent    spring boot 完成Environment的装载但是还没有开始applicationContext的装载的时候触发(它和实现了EnvironmentAware不一样,后者时需要Bean被装载进去后才调用)

3.ApplicationPreparedEvent  springboot 完成上下文的创建,单还没有完全完成bean的装载

4.ApplicationFailedEvent spring boot启动异常时触发。

spring boot内部本身就有很多listener,他们分别监听上面几种事件,这里就不再赘述,有兴趣的同学可以研究一下spring boot的源码。

Spring Boot 的详细介绍:请点这里

Spring Boot 的下载地址:请点这里

总结

以上是生活随笔为你收集整理的Linux新建yaml文件,Spring Boot 装载自定义yml文件的全部内容,希望文章能够帮你解决所遇到的问题。

如果觉得生活随笔网站内容还不错,欢迎将生活随笔推荐给好友。