網頁

2020/12/22

Spring Boot use SPRING_APPLICATION_JSON environment variable properties in Windows

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=hellodemo.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中分別用@ValueEnvironment.getProperty()取得demo.var1demo.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的設定。


沒有留言:

張貼留言