Springboot 中配置文件的優先級和加載順序


1. 若application.yml 和bootStrap.yml 在同一目錄下,則bootStrap.yml 的加載順序要高於application.yml,即bootStrap.yml  會優先被加載。

   原理:bootstrap.yml 用於應用程序上下文的引導階段。

              bootstrap.yml 由父Spring ApplicationContext加載。

            •bootstrap.yml 可以理解成系統級別的一些參數配置,這些參數一般是不會變動的。
            •application.yml 可以用來定義應用級別的,如果搭配 spring-cloud-config 使用 application.yml 里面定義的文件可以實現動態替換。

 

 

2. 不同位置的配置文件的加載順序:

   在不指定要被加載文件時,默認的加載順序:由里向外加載,所以最外層的最后被加載,會覆蓋里層的屬性(參考官網介紹)

SpringApplication will load properties from application.properties files in the following locations and add them to the Spring Environment: 

A /config subdirectory of the current directory.    //位於與jar包同級目錄下的config文件夾,
The current directory                             //位於與jar包同級目錄下
A classpath /config package          //idea 環境下,resource文件夾下的config文件夾
The classpath root                                //idea 環境下,resource文件夾下  (1->4, 外->里)
The list is ordered by precedence (properties defined in locations higher in the list override those defined in lower locations).

 

3. 可以通過屬性指定加載某一文件:

java -jar myproject.jar --spring.config.location=classpath:/default.properties,classpath:/override.properties
當通過spring.config.location 指定一個配置文件時,配置文件的搜索順序如下:

file:./custom-config/
classpath:custom-config/
file:./config/
file:./
classpath:/config/
classpath:/
最下層的優先加載,所以最上層的屬性會覆蓋下層的屬性;

 

4. 如果使用spring-cloud-config時,項目內部的resource下有bootstrap.yml文件,並且在bootstrap.yml 里配置spring.application.name, git.url,spring.active.profies. 將項目打成jar包,放到服務器上,與jar包並列的位置,有start.sh腳本, 

a. 在start 腳本里指定了配置文件:spring.config.location=./bootstrap.yml, 則配置文件的加載順序將為:

1. cloud-config 倉庫里指定的yml 配置;

2. ./bootstrap.yml

3. classpath:/bootstrap.yml

4. 外部application.yml

5. 內部application.yml

b. 在start 腳本里指定了配置文件:spring.config.location=./application.yml, 則配置文件的加載順序將為:

1. cloud-config 倉庫里指定的yml 配置;

2. ./application.yml

3.  classpath:/application.yml

4. ./bootstrap.yml

5. classpath:/bootstrap.yml

所以,不管是jar包內還是jar運行的同級目錄下,只要包含bootstrap.yml ,且為雲配置,則雲配置文件會覆蓋其他配置文件;

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM