spring boot裝載自定義yml文件
yml格式的配置文件感覺很人性化,所以想把項目中的.properties都替換成.yml文件,主要springboot自1.5以后就把@configurationProperties中的location參數(shù)去掉,各種查詢之后發(fā)現(xiàn)可以用YamlPropertySourceLoader去裝載yml文件,上代碼
public void onApplicationEvent(ApplicationEnvironmentPreparedEvent event) {
ResourceLoader loader = new DefaultResourceLoader();
YamlPropertySourceLoader yamlLoader = new YamlPropertySourceLoader();
List<String> 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);
}
});
}
這里主要實現(xiàn)了spring boot的ApplicationListener<ApplicationEnvironmentPreparedEvent>接口,spring boot為我們提供了四種監(jiān)聽事件:
1.ApplicationStartedEvent spring boot 剛啟動時會觸發(fā)事件
2.ApplicationEnvironemntPreparedEvent spring boot 完成Environment的裝載但是還沒有開始applicationContext的裝載的時候觸發(fā)(它和實現(xiàn)了EnvironmentAware不一樣,后者時需要Bean被裝載進去后才調用)
3.ApplicationPreparedEvent springboot 完成上下文的創(chuàng)建,單還沒有完全完成bean的裝載
4.ApplicationFailedEvent spring boot啟動異常時觸發(fā)。
spring boot內部本身就有很多l(xiāng)istener,他們分別監(jiān)聽上面幾種事件,這里就不再贅述,有興趣的同學可以研究一下spring boot的源碼。
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持腳本之家。
相關文章
ArrayList與linkedList的用法區(qū)別及擴容方式
這篇文章主要介紹了ArrayList與linkedList的用法區(qū)別及擴容方式,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2023-03-03
使用RequestBodyAdvice實現(xiàn)對Http請求非法字符過濾
這篇文章主要介紹了使用RequestBodyAdvice實現(xiàn)對Http請求非法字符過濾的操作,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2021-06-06
關于eclipse中運行tomcat提示端口被占用的4種解決
這篇文章主要介紹了關于eclipse中運行tomcat提示端口被占用的4種解決,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2023-01-01
spring cloud Hystrix斷路器的使用(熔斷器)
這篇文章主要介紹了spring cloud Hystrix斷路器的使用(熔斷器),小編覺得挺不錯的,現(xiàn)在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧2018-08-08

