溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務(wù)條款》

spring boot裝載自定義yml文件

發(fā)布時間:2020-09-15 16:21:13 來源:腳本之家 閱讀:159 作者:在山的那邊 欄目:編程語言

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被裝載進去后才調(diào)用)

3.ApplicationPreparedEvent   springboot 完成上下文的創(chuàng)建,單還沒有完全完成bean的裝載

4.ApplicationFailedEvent   spring boot啟動異常時觸發(fā)。

spring boot內(nèi)部本身就有很多l(xiāng)istener,他們分別監(jiān)聽上面幾種事件,這里就不再贅述,有興趣的同學(xué)可以研究一下spring boot的源碼。

以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持億速云。

向AI問一下細節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進行舉報,并提供相關(guān)證據(jù),一經(jīng)查實,將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI