简介
Spring在创建容器时,会创建Environment环境对象,用于保存spring应用程序的运行环境相关的信息。在创建环境时,需要创建属性源属性解析器,会解析属性值中的占位符,并进行替换。
- 针对
Spring 非Web 应用
===>StandardEnvironment
- 针对
Spring Servlet Web 应用
===>StandardServletEnvironment
AbstractEnvironment
// 指示Spring忽略系统环境变量,默认值为"false"。
// false表示不会忽略系统环境变量,此时getSystemEnvironment方法会调用System.getenv()获取环境属性
// true表示会忽略系统的环境变量,此时getSystemEnvironment方法会返回一个空的Map
public static final String IGNORE_GETENV_PROPERTY_NAME = "spring.getenv.ignore";
// 指定系统启动时使用哪些配置文件,可以使用逗号隔开
public static final String ACTIVE_PROFILES_PROPERTY_NAME = "spring.profiles.active";
// 指定系统启动时使用默认的配置文件,可以使用逗号隔开
public static final String DEFAULT_PROFILES_PROPERTY_NAME = "spring.profiles.default";
// 保留的默认的配置文件的名称,如果没有显式设置默认配置文件名称,也没有显式设置活动配置文件名称,则默认情况下该配置文件将自动激活
protected static final String RESERVED_DEFAULT_PROFILE_NAME = "default";
// 日志对象
protected final Log logger = LogFactory.getLog(getClass());
//系统启动时使用的配置文件
private final Set<String> activeProfiles = new LinkedHashSet<>();
// 默认配置文件
private final Set<String> defaultProfiles = new LinkedHashSet<>(getReservedDefaultProfiles());
// 可变属性源,使用该成员变量保存属性源及通过该属性源获取的属性
private final MutablePropertySources propertySources;
// 可配置的属性解析器
private final ConfigurablePropertyResolver propertyResolver;
//设置多个环境下的配置文件
@Override
public void setDefaultProfiles(String... profiles) {
Assert.notNull(profiles, "Profile array must not be null");
synchronized (this.defaultProfiles) {
this.defaultProfiles.clear();
for (String profile : profiles) {
validateProfile(profile);
this.defaultProfiles.add(profile);
}
}
}
实现类StandardEnvironment
/** 来自 system.getProperties() 以系统环境为属性源*/
public static final String SYSTEM_ENVIRONMENT_PROPERTY_SOURCE_NAME = "systemEnvironment";
/** 来自 system.getenv() 以JVM系统属性为属性源*/
public static final String SYSTEM_PROPERTIES_PROPERTY_SOURCE_NAME = "systemProperties";
示例
@Test
public void testEnvironment(){
//创建一个标准环境
StandardEnvironment env = new StandardEnvironment();
//定义一个PropertySource 存放我们定义的数据
Properties properties = new Properties();
properties.setProperty("testEnvData","测试Evn数据");
PropertySource source = new PropertiesPropertySource("key_testERvnData",properties);
MutablePropertySources propertySources = env.getPropertySources();
//将我们定义的PropertySource加入到Spring环境中
propertySources.addLast(source);
//从Spring环境中获取
System.out.println(env.getProperty("testEnvData"));
}