springboot讀取系統級環境變量,和讀寫系統屬性以及unittest來獲取環境變量的方法


 

環境變量的讀取以及系統屬性的設置 環境變量只能讀取,不能修改,系統屬性可以修改

系統變量的讀取方式: 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")); } } 

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM