所有系统属性,环境变量和应用程序属性都由Environment提供,spring启动时将填充该接口
package com.apress.prospring5.ch4;
import org.springframework.context.support.GenericXmlApplicationContext;
import org.springframework.core.env.ConfigurableEnvironment;
import org.springframework.core.env.MapPropertySource;
import org.springframework.core.env.MutablePropertySources;
import java.util.HashMap;
import java.util.Map;
public class EnvironmentSampleFirst {
public static void main(String... args) {
GenericXmlApplicationContext ctx = new GenericXmlApplicationContext();
ctx.refresh();
ConfigurableEnvironment env = ctx.getEnvironment();
MutablePropertySources propertySources = env.getPropertySources();
Map<String,Object> appMap = new HashMap<>();
appMap.put("user.home", "application_home");
//addFirst
propertySources.addFirst(new MapPropertySource("prospring5_MAP", appMap));
System.out.println("user.home: " + System.getProperty("user.home"));
System.out.println("JAVA_HOME: " + System.getenv("JAVA_HOME"));
System.out.println("user.home: " + env.getProperty("user.home"));
System.out.println("JAVA_HOME: " + env.getProperty("JAVA_HOME"));
ctx.close();
}
}
执行结果
user.home: /Users/chujun
JAVA_HOME: /Library/Java/JavaVirtualMachines/jdk1.8.0_211.jdk/Contents/Home
user.home: application_home
JAVA_HOME: /Library/Java/JavaVirtualMachines/jdk1.8.0_211.jdk/Contents/Home
debug查看属性源列表如截图
Environment propertySources列表.png
package com.apress.prospring5.ch4;
import org.springframework.context.support.GenericXmlApplicationContext;
import org.springframework.core.env.ConfigurableEnvironment;
import org.springframework.core.env.MapPropertySource;
import org.springframework.core.env.MutablePropertySources;
import java.util.HashMap;
import java.util.Map;
public class EnvironmentSampleLast {
public static void main(String... args) {
GenericXmlApplicationContext ctx = new GenericXmlApplicationContext();
ctx.refresh();
ConfigurableEnvironment env = ctx.getEnvironment();
MutablePropertySources propertySources = env.getPropertySources();
Map<String,Object> appMap = new HashMap<>();
appMap.put("application.home", "application_home");
//addLast
propertySources.addLast(new MapPropertySource("prospring5_MAP", appMap));
System.out.println("user.home: " + System.getProperty("user.home"));
System.out.println("JAVA_HOME: " + System.getenv("JAVA_HOME"));
System.out.println("user.home: " + env.getProperty("user.home"));
System.out.println("JAVA_HOME: " + env.getProperty("JAVA_HOME"));
System.out.println("application.home: " + env.getProperty("application.home"));
ctx.close();
}
}
user.home: /Users/chujun
JAVA_HOME: /Library/Java/JavaVirtualMachines/jdk1.8.0_211.jdk/Contents/Home
user.home: /Users/chujun
JAVA_HOME: /Library/Java/JavaVirtualMachines/jdk1.8.0_211.jdk/Contents/Home
application.home: application_home
网友评论