在spring boot中所有参数都被理解为当前项目运行的环境变量。spring boot环境的初始化操作在ConfigurableApplicationContex
t的创建之前,功实现主要依赖PropertyResolver
和PropertySource
这两个接口。
1. PropertyResolver接口
spring boot项目的非web项目会创建StandardEnvironment
类并完成初始化参数的加载,web项目中则创建的为StandardServletEnvironment
类来完成参数的初始化,其类层次关系如下
- PropertyResolver:提供属性访问功能。
- ConfigurablePropertyResolver :继承自
PropertyResolver
,额外主要提供属性类型转换(基于org.springframework.core.convert.ConversionService
)功能。 - Environment:继承自
PropertyResolver
,额外提供访问和判断profiles的功能。 - ConfigurableEnvironment:继承自
ConfigurablePropertyResolver
和Environment
,并且提供设置激活的profile和默认的profile的功能。 - ConfigurableWebEnvironment:继承自
ConfigurableEnvironment
,并且提供配置Servlet上下文和Servlet参数的功能。 - AbstractEnvironment:实现了
ConfigurableEnvironment
接口,默认属性和存储容器的定义,并且实现了ConfigurableEnvironment
种的方法,并且为子类预留可覆盖了扩展方法。 - StandardEnvironment:继承自
AbstractEnvironment
,非Servlet(Web)环境下的标准Environmen
t实现。 - StandardServletEnvironment:继承自
StandardEnvironment
,Servlet(Web)环境下的标准Environment
实现。
2. PropertySource接口
PropertySource
为真实参数存储的地方,Environment
的静态属性和存储容器都是在AbstractEnvironment
中定义的,ConfigurableWebEnvironment
接口提供的getPropertySources()
方法可以获取到返回的MutablePropertySources
实例,然后添加额外的PropertySource
。实际上,Environment
的存储容器就是org.springframework.core.env.PropertySource
的子类集合,如下图:
PropertySource
的常用类层次关系如下:
- MapPropertySource:
source
指定为Map实例的PropertySource
实现。 - PropertiesPropertySource:
source
指定为Map实例的PropertySource
实现,内部的Map
实例由Properties
实例转换而来。 - ResourcePropertySource:继承自
PropertiesPropertySource
,source
指定为通过Resource
实例转化为Properties
再转换为Map实例。 - StubPropertySource:
PropertySource
的一个内部类,source
设置为null
,实际上就是空实现。 - OriginTrackedMapPropertySource:获取value值时,如果value为
OriginTrackedValue
,则调用value的getValue
方法循环一直找到最原始的值
3. 环境初始化代码分析
- 从SpringApplication.run入手
public ConfigurableApplicationContext run(String... args) {
…………
try {
ApplicationArguments applicationArguments = new DefaultApplicationArguments(
args);
//Environment创建和初始化地方,在ApplicationContext创建之前
ConfigurableEnvironment environment = prepa