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文件的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: arm体系结构与编程_RISCV中文版面
- 下一篇: vue-router路由安装与使用