环境变量的读取以及系统属性的设置 环境变量只能读取,不能修改,系统属性可以修改
系统变量的读取方式: System.getEnv()
系统属性有多重读取和修改方式:
其修改方式为:
- 读取系统属性:
@Autowired
AbstractEnvironment environment;
System.setProperty("today","tuesday"); environment.getProperty("test");
- 增加新的系统属性:
Map<String, Object> map = new HashMap<String, Object>(); map.put("hello","world"); MapPropertySource mapPropertySource = new MapPropertySource("VCAP_SERVICES", map); environment.getPropertySources().addLast(mapPropertySource); environment.getPropertySources().addFirst(mapPropertySource);
Test获取系统环境变量
有时候业务中需要读取环境变量时,而unittest又读取不到环境变量,System.getEnv()的值是null 此时就用到一个开源的包来解决这个问题了
testCompile("com.github.stefanbirkner:system-rules:1.16.1")
使用方法
创建一个自定义的SpringJUnit4ClassRunner类来集成SpringJUnit4ClassRunner类,设置环境变量, 其中@Rule注解代表可以运行在测试过程中创建临时文件或者临时目录,当测试结束后,框架会自动删除。
package tools; import org.junit.Rule; import org.junit.contrib.java.lang.system.EnvironmentVariables; import org.junit.runners.model.InitializationError; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; public class MySpringJUnit4ClassRunner extends SpringJUnit4ClassRunner { @Rule public final EnvironmentVariables environmentVariables = new EnvironmentVariables(); /** * Construct a new {@code SpringJUnit4ClassRunner} and initialize a * {@link TestContextManager} to provide Spring testing functionality to * standard JUnit tests. * * @param clazz the test class to be run * @see #createTestContextManager(Class) */ public MySpringJUnit4ClassRunner(Class<?> clazz) throws InitializationError { super(clazz); String str="hello world!"; environmentVariables.set("test", str); } }
下面是unittest
package tools; import org.junit.Assert; import org.junit.Test; import org.junit.runner.RunWith; import tools.MySpringJUnit4ClassRunner; @RunWith(MySpringJUnit4ClassRunner.class) public class Test { @Test public void should_return_test() throws AppException { System.out.println(System.getenv("test")); Assert.assertEquals("hello world", redisService.get("test")); } }