springBoot配置加载顺序
参考
https://docs.spring.io/spring-boot/docs/2.3.9.RELEASE/reference/htmlsingle/#boot-features-external-config https://docs.spring.io/spring-boot/docs/current/reference/html/features.html#features.external-config spring2.0与3.0版本的加载顺序不一致, 差异在于config data file的加载顺序不同.
注意: 请以springboot启动流程中配置文件的加载顺序,后加载覆盖先加载
来考虑,而不是配置的优先级
来考虑. 这样会得到更准确的结果, 也更符合直觉.
PropertySource顺序
加载顺序如下, 下面的覆盖上面的.
Default properties (specified by setting SpringApplication.setDefaultProperties).
@PropertySource annotations on your @Configuration classes. Please note that such property sources are not added to the Environment until the application context is being refreshed. This is too late to configure certain properties such as logging.* and spring.main.* which are read before refresh begins.
Config data (such as application.properties files).
A RandomValuePropertySource that has properties only in random.*.
OS environment variables.
Java System properties (System.getProperties()).
JNDI attributes from java:comp/env.
ServletContext init parameters.
ServletConfig init parameters.
Properties from SPRING_APPLICATION_JSON (inline JSON embedded in an environment variable or system property).
Command line arguments.
properties attribute on your tests. Available on @SpringBootTest and the test annotations for testing a particular slice of your application.
@DynamicPropertySource annotations in your tests.
@TestPropertySource annotations on your tests.
Devtools global settings properties in the $HOME/.config/spring-boot directory when devtools is active.
config data file 加载
对上面第3点的细化.
优先级原则
以下原则也有优先级, 优先级依此降低.
- bootstrap > application, 由于spring-boot启动时,会先用bootstrap中的配置文件初始化上下文, 在用application初始化子上下文,所以在springboot的整体流程上,bootstrap优先被使用. 但是这不意味着bootstrap中的配置优先级高于application中的配置, 事实上,除了在启动流程上导致的优先级不同, 在我们使用普通配置时, application配置的优先级高于bootstrap, 因为application被后加载,所以会覆盖bootstrap中的配置.
- profile > 非profile, 与文件目录无关. 所有的profile文件永远优先于非profile文件.
- 位置优先级,见下面
- 同一目录下, properties > yml > yaml
位置顺序
加载顺序如下, 下面的覆盖上面的. classpath/ classpath/config/ jar包所在目录/ jar包所在目录/config/
举例
假设当前目录为 app/test.jar, 则文件加载的顺序如下, 下面的覆盖上面的.
# 硬编码的配置
@PropertySource
# 配置文件:先加载非profile
app/test.jar/classpath/application.properties/yml/yaml
app/test.jar/classpath/config/application.properties/yml/yaml
app/application.properties
app/config/application.properties
# 配置文件:再加载profile
app/test.jar/classpath/application-profile.properties/yml/yaml
app/app/test.jar/classpath/config/application-profile.properties/yml/yaml
app/application-profile.properties
app/config/application-profile.properties
# 运行时指定的配置
操作系统环境变量中的配置
JVM系统属性中的配置
JNDI attributes from java:comp/env.
执行命令传入的配置
properties attribute on tests