環境變量的讀取以及系統屬性的設置 環境變量只能讀取,不能修改,系統屬性能夠修改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")); } }