Springboot 中配置文件的优先级和加载顺序

1. 若application.yml 和bootStrap.yml 在同一目录下,则bootStrap.yml 的加载顺序要高于application.yml,即bootStrap.yml  会优先被加载。java

   原理:bootstrap.yml 用于应用程序上下文的引导阶段。git

              bootstrap.yml 由父Spring ApplicationContext加载。spring

            •bootstrap.yml 能够理解成系统级别的一些参数配置,这些参数通常是不会变更的。
            •application.yml 能够用来定义应用级别的,若是搭配 spring-cloud-config 使用 application.yml 里面定义的文件能够实现动态替换。bootstrap

 

 

2. 不一样位置的配置文件的加载顺序:服务器

   在不指定要被加载文件时,默认的加载顺序:由里向外加载,因此最外层的最后被加载,会覆盖里层的属性(参考官网介绍)app

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

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).url

 

3. 能够经过属性指定加载某一文件:idea

java -jar myproject.jar --spring.config.location=classpath:/default.properties,classpath:/override.properties
当经过spring.config.location 指定一个配置文件时,配置文件的搜索顺序以下:spa

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 ,且为云配置,则云配置文件会覆盖其余配置文件;

相关文章
相关标签/搜索