0%

System Environment 和 System Properties

System Environment 指的是操作系统的环境变量,而 System Properties 指的是java 程序jvm的系统变量

System Environment

1
2
3
4
// 获取全部的环境变量
Map<String, String> systemEnvironment = System.getenv();
// 获取某个环境变量 比如:PATH
String path = System.getenv("PATH");

System Properties

1
2
3
4
// 获取所有的环境变量
Properties properties = System.getProperties();
// 获取指定的环境变量 如java.class.path
String property = System.getProperty("java.class.path");

设置jvm的系统变量有两种方式:

  1. 通过java -Dkey=value 参数设置,如果value有空格,需要用双引号括起来
  2. 在代码里通过System.setProperty(key, value)进行设置

Spring Environment

在Spring通过EnvironmentCapable接口中的**getEnvironment()**方法可以获取当前环境变量。

image-20220628222003595

如上图所示,ApplicationContext实现了EnvironmentCapable接口,具体的实现方法是在AbstractApplicationContext中。

关于Environment接口类图如下图所示:

image-20220628223346896

Environment创建

getEnvironment()

AbstractApplicationContext类

1
2
3
4
5
6
public ConfigurableEnvironment getEnvironment() {
if (this.environment == null) {
this.environment = createEnvironment();
}
return this.environment;
}

createEnvironment()

AbstractApplicationContext类

1
2
3
protected ConfigurableEnvironment createEnvironment() {
return new StandardEnvironment();
}

因为StandardEnvironment继承自AbstractEnvironment,将调用父类的构造方法。

AbstractEnvironment()

AbstractEnvironment类

1
2
3
public AbstractEnvironment() {
this(new MutablePropertySources());
}

AbstractEnvironment(MutablePropertySources propertySources)

AbstractEnvironment类

1
2
3
4
5
protected AbstractEnvironment(MutablePropertySources propertySources) {
this.propertySources = propertySources;
this.propertyResolver = createPropertyResolver(propertySources);
customizePropertySources(propertySources);
}

customizePropertySources(MutablePropertySources propertySources)

StandardEnvironment类

1
2
3
4
5
6
7
@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()));
}

优先级结论

在调用getProperty()方法时从propertySources集合按照添加顺序获取值,可以看出来SYSTEM_PROPERTIES优先级高于SYSTEM_ENVIRONMENT