1. 源码分析
Intellij idea Diagrams
上图看不懂,重画一张如下:
经上分析,得知 StandardEnvironment 主要功能用于获取和设置应用程序的属性和环境。
2. 得到下列问题:
- 属性是什么?
- 环境是什么?
- 属性和环境从那儿来,到那儿去?
属性 和 环境 是什么,阅读 StandardEnvironment 和 AbstractEnvironment 得到答案。
StandardEnvironment.java 第77行
@Override
protected void customizePropertySources(MutablePropertySources propertySources) {
propertySources.addLast(new PropertiesPropertySource(SYSTEM_PROPERTIES_PROPERTY_SOURCE_NAME, getSystemProperties()));
propertySources.addLast(new SystemEnvironmentPropertySource(SYSTEM_ENVIRONMENT_PROPERTY_SOURCE_NAME, getSystemEnvironment()));
}
getSystemProperties() 此方法获取属性。
AbstractEnvironment.java 第387行
public Map<String, Object> getSystemProperties() {
try {
return (Map) System.getProperties();
}
// 其他省略...
}
直接调用 System.getProperties(); 方法获取java系统属性返回。
System.getProperties(); 打印如下:
getSystemEnvironment() 此方法获取环境。
AbstractEnvironment.java 第413行
public Map<String, Object> getSystemEnvironment() {
if (suppressGetenvAccess()) {
return Collections.emptyMap();
}
try {
return (Map) System.getenv();
}
其他省略...
}
先检查 SpringProperties 是否存在 spring.getenv.ignore 环境变量,如果不存在则则查询 System.getProperties(); 是否存在。如果值为true则返回空的Map对象EmptyMap,如果存在则获取系统环境System.getenv()返回。
System.getenv() 打印如下:
实际测试一次,确实没有获取到 Java 环境给出空Map作为返回
问题解答完成,下一个。
属性和环境放在那儿了?在这里得到答案。
StandardEnvironment.java 第77行
@Override
protected void customizePropertySources(MutablePropertySources propertySources) {
propertySources.addLast(new PropertiesPropertySource(SYSTEM_PROPERTIES_PROPERTY_SOURCE_NAME, getSystemProperties()));
propertySources.addLast(new SystemEnvironmentPropertySource(SYSTEM_ENVIRONMENT_PROPERTY_SOURCE_NAME, getSystemEnvironment()));
}
可以看到 MutablePropertySources.addLast(); 方法,为啥将 属性 和 环境 丢进去。
实现了迭代接口,拥有了存储数据功能。
MutablePropertySources.java 第44行
MutablePropertySources implements PropertySources {
private final List<PropertySource<?>> propertySourceList = new CopyOnWriteArrayList<>();
省略代码...
}
内部使用了一个 CopyOnWriterArrayList 用来存放数据。
数据结构为:
MutablePropertySources.java 第44行集合
[
PropertiesPropertySource: PropertySource {
name: '属性名',
source: {
key1: value1,
key2: value2
}
}
]
至此存放集合分析完成。
结合 ConfigurableConversionService,MutablePropertySources 前者做数据转换,后者做数据存储。
PropertySourcesPropertyResolver 负责类型转换:将读取到的 时间,整数,浮点等一些基础数据进行数据转换。
简单给个使用案例:
功能特点:
1.查询数据按照数组顺序查询,若有重复的取第一个
2.数据取出时会自动转换为指定类型,默认String 类型
SpringBoot转换服务ApplicationConversionService
至此完成。