Spring Boot可在系統設定環境變數SPRING_APPLICATION_JSON
的json格式變數注入properties。
範例環境:
- Windows 7 64 bit
- Spring Boot 2.3.2.RELEASE
- JUnit 5
- Maven 3.6.3
以Windows系統為例,在命令提示字元 cmd 輸入
set SPRING_APPLICATION_JSON={"demo.var1":"hello", "demo.var2":"world"}
設定系統環境變數SPRING_APPLICATION_JSON
的json。
{
"demo.var1":"hello",
"demo.var2":"world"
}
json中帶入demo.var1=hello
及demo.var2=world
兩個properties。
D:\>set SPRING_APPLICATION_JSON={"demo.var1":"hello", "demo.var2":"world"}
D:\>echo %SPRING_APPLICATION_JSON%
{"demo.var1":"hello", "demo.var2":"world"}
下面DemoService
bean中分別用@Value
及Environment.getProperty()
取得demo.var1
及demo.var2
。
DemoService
package com.abc.demo.service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.env.Environment;
import org.springframework.stereotype.Service;
@Service
public class DemoService {
@Value("${demo.var1}")
private String var1;
@Value("${demo.var2}")
private String var2;
@Autowired
private Environment env;
public String[] getVarsFromValueInject() {
return new String[]{var1, var2};
}
public String[] getVarsFromEnvironment() {
String var1 = env.getProperty("demo.var1");
String var2 = env.getProperty("demo.var2");
return new String[]{var1, var2};
}
}
測試程式DemoServiceTests
。
DemoServiceTests
package com.abc.demo.service;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
@SpringBootTest
public class DemoServiceTests {
@Autowired
private DemoService demoService;
@Test
public void getVarsFromValueInject() {
String[] vars = demoService.getVarsFromValueInject();
Assertions.assertEquals("hello", vars[0]);
Assertions.assertEquals("world", vars[1]);
}
@Test
public void getVarsFromEnvironment() {
String[] vars = demoService.getVarsFromEnvironment();
Assertions.assertEquals("hello", vars[0]); // pass
Assertions.assertEquals("world", vars[1]); // pass
}
}
SPRING_APPLICATION_JSON
會覆蓋application.properties
的設定。
沒有留言:
張貼留言