Config使用
Config本地配置文件加载原理分析
Config配置中心配置加载原理分析
本文主要内容:
- 简要了解PropertySource配置源体系结构
- 了解Springboot中,每个PropertySource优先级
- 了解Springboot是如何加载application.properties配置文件,即:ConfigFileApplicationListener
- 了解SpringCloud中的BootstrapApplicationListener及作用
一、Spring本地配置文件加载
1.1、Spring PropertySource配置源体系结构
其中有一些我们常见的属性源,如:
- CommandLinePropertySource命令行属性源
- SystemEnvironmentPropertySource系统环境变量属性源
- CompositePropertySource组合属性源
- MutablePropertySources可变属性源
二、SpringBoot本地配置文件加载
2.1、官方定义SpringBoot配置源加载顺序
因为PropertySource是存在一个List中的,因此PropertySource之间是有序的
,而在Springboot官网中的(2.Externalized Configuration)章节,对PropertySource的优先级顺序进行了说明:
Spring Boot uses a very particular PropertySource order that is designed to allow sensible overriding of values. Properties are considered in the following order:
Devtools global settings properties in the $HOME/.config/spring-boot directory when devtools is active.
@TestPropertySource annotations on your tests.
properties attribute on your tests. Available on @SpringBootTest and the test annotations for testing a particular slice of your application.
Command line arguments.
Properties from SPRING_APPLICATION_JSON (inline JSON embedded in an environment variable or system property).
ServletConfig init parameters.
ServletContext init parameters.
JNDI attributes from java:comp/env.
Java System properties (System.getProperties()).
OS environment variables.
A RandomValuePropertySource that has properties only in random.*.
Profile-specific application properties outside of your packaged jar (application-{profile}.properties and YAML variants).
Profile-specific application properties packaged inside your jar (application-{profile}.properties and YAML variants).
Application properties outside of your packaged jar (application.properties and YAML variants).
Application properties packaged inside your jar (application.properties and YAML variants).
@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.
Default properties (specified by setting SpringApplication.setDefaultProperties).
其中我们常用的有:
加载顺序 | 资源类型 | 设置方式 |
---|---|---|
4 | Command line arguments | 命令行参数,通过java -jar --name=”Spring” |
6 | ServletConfig init parameters | ServletConfig配置的init参数 |
7 | ServletContext init parameters | ServletContext配置的init参数 |
9 | <