Springboot 加載application.yml 擴展及小tips

寫在文章前

問題1:
假如我的spring boot項目配置了 application.yml,application-dev.yml,application.yml 三個文件分別配置服務端口爲8080,8081,8082

spring:
  profiles:
    active: pro,dev
spring:
  profiles:
    active: dev,pro

問上面這兩個配置啓動後服務的端口是什麼?

問題2:

有一個依賴的jar中採用的Properties進行取值的,而且寫死了文件路徑classpath:…
但是有一個init初始化方法,想將其改造爲支持application.yml取值的並且優先級是
application.yml>target.properties

Spring Boot 版本

因爲網上好多講這部分的都沒有列出spring boot版本,導致大家不能debug源碼,遂標出版本號

 <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.1.6.RELEASE</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>

大致流程

1.項目通過run方法啓動
在這裏插入圖片描述
2.找到核心位置

ConfigurableEnvironment environment = prepareEnvironment(listeners, applicationArguments);

3.仔細閱讀
在這裏插入圖片描述
4.enviroment創建完畢後會執行的事件
ApplicationPreparedEvent

擴展

核心是瞭解Spring的事件順序,根據事件進行切入

開始擴展

1.切入EnvironmentPostProcessor 設置Order,設置爲在application.yml前還是後

2.監聽Spring事件,我大致看了下代碼,在Environment準備完畢後會進行ApplicationPreparedEvent事件遂對其進行切入

3.學習Environment的getProperty處理流程

4.MutablePropertySources加載資源流程

注意點

事件需要在META-INF/spring.factories進行註冊

org.springframework.boot.env.EnvironmentPostProcessor=\

org.springframework.context.ApplicationListener=\

因項目涉及到公司就不放出來了,有問題發留言即可。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章