环境变量的读取以及系统属性的设置 环境变量只能读取,不能修改,系统属性能够修改java
系统变量的读取方式: System.getEnv()git
系统属性有多重读取和修改方式:github
其修改方式为:redis
@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获取系统环境变量spring
有时候业务中须要读取环境变量时,而unittest又读取不到环境变量,System.getEnv()的值是null 此时就用到一个开源的包来解决这个问题了框架
testCompile("com.github.stefanbirkner:system-rules:1.16.1")
使用方法ide
建立一个自定义的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); } }
下面是unittestcode
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")); } }