理解 Spring Environment 抽象
- 统一的Spring配置属性管理
Spring Framework 3.1开始引入Environment抽象,它统一Spring配置属性的存储/包括占位符处理和类型转
换,不仅完整地替换PropertyPlaceholderConfigurer,而且还支持更丰富的配置属性源(Propertysource) - 条件化Spring Bean装配管理
通过Environment Profiles信息/帮助Spring容器提供条件化地装配Bean
Spring Environment 接口使用场景
用于属性占位符处理
用于转换Spring配置属性类型
用于存储Spring配置属性源(Propertysource) •用于Profiles状态的维护
依赖注入Environment
- 直接依赖注入
通过 EnvironmentAware 接口回调
通过 @Autowired 注入 Environment - 间接依赖注入
通过 ApplicationContextAware 接口回调
通过 @Autowired 注入 Applicationcontext
依赖查找Environment
- 直接依赖查找
- 通过org.springframework.context,ConfigurableApplicationContext#ENVIRONMENT_BEAN_NAME
- 间接依赖查找
通过 org.springframework.context.ConfigurableApplicationContext#getEnvironment
Spring类型转换在Environment中的运用
- 底层实现-org.springframework.core.env.PropertySourcesPropertyResolver
核心方法-convertValuelfNecessary(Object7Class) - 底层服务-org.springframework.core.convert.ConversionService
默认实现-org.springframework.core.convert.support.DefaultConversionService
Spring类型转换在@Value中的运用
- 底层实现-org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor
org.springframework.beans.factory.support.DefaultListableBeanFactory#doResolveDependency - 底层服务-org.springframework.beans.TypeConverter
默认实现-org.springframework.beans.TypeConverterDelegate
ava.beans.PropertyEditor
org.springframework.core.convert.ConversionService
Spring 配置属性源 Propertysource
- API
单配置属性源-org.springframework.core.env.PropertySource
多配置属性源-org.springframework.core.env.PropertySources - 注解
– 单配置属性源-@org.springframework.context.annotation.PropertySource
– 多配置属性源-@org.springframework.context.annotation.PropertySources •关联
– 存储对象-org.springframework.core.env.MutablePropertySources
– 关联方法-org.springframework.core.env.ConfigurableEnvironment#getPropertySources()