yml格式的配置文件感覺很人性化,所以想把項目中的.properties都替換成.yml文件,主要springboot自1.5以后就把@configurationProperties中的location參數去掉,各種查詢之后發現可以用YamlPropertySourceLoader去裝載yml文件,上代碼
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
32
|
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); } }); } |
這里主要實現了spring boot的ApplicationListener<ApplicationEnvironmentPreparedEvent>接口,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的源碼。
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持服務器之家。