如何从Spring Boot获取OS环境变量?

时间:2018-07-10 10:23:33

标签: java spring environment-variables

我是Java和Spring框架的新手。我的问题是如何将OS(ubuntu)环境变量注入spring boot bean。我尝试过的:

@Configuration
@EnableWebMvc
public class CorsConfig implements WebMvcConfigurer {
 @Value("${COMPONENT_PARAM_CORS}")
 private String COMPONENT_PARAM_CORS;

 @Override
 public void addCorsMappings(CorsRegistry registry) {
  registry.addMapping("/"+COMPONENT_PARAM_CORS);
 }
}

导出COMPONENT_PARAM_CORS = **

printenv

告诉我它存在,但是当我尝试mvn全新安装:发生错误

java.lang.IllegalStateException: Failed to load ApplicationContext
Caused by: org.springframework.beans.factory.BeanCreationException: Error 
creating bean with name 'corsConfig': Injection of autowired dependencies 
failed; nested exception is java.lang.IllegalArgumentException: Could not 
resolve placeholder 'COMPONENT_PARAM_CORS' in value "${COMPONENT_PARAM_CORS}"
Caused by: java.lang.IllegalArgumentException: Could not resolve placeholder 
'COMPONENT_PARAM_CORS' in value "${COMPONENT_PARAM_CORS}"

然后我的单元测试也下降了 (我正在尝试搜索此错误,但是所有主题都很旧,并且使用了application.properties中的参数,但是我需要使用env var而不是application.properties)

3 个答案:

答案 0 :(得分:4)

您可以使用System.getenv(<environment name>)方法来检索环境变量值。喜欢:

registry.addMapping("/" + System.getenv("COMPONENT_PARAM_CORS"));

或具有默认值:

registry.addMapping("/" + System.getenv().getOrDefault("COMPONENT_PARAM_CORS", "DEFAULT_VALUE"))

更多信息,请点击https://docs.oracle.com/javase/tutorial/essential/environment/env.html

如果您确实要注入变量值,则可以将代码修改为:

@Value("#{systemEnvironment['COMPONENT_PARAM_CORS'] ?: 'DEFAULT_VALUE'}")
private String COMPONENT_PARAM_CORS;

答案 1 :(得分:1)

您应使用System.getenv(),例如:

open FSharp.Data

[<Literal>]
let json = """{ "table": [ {"boolean": true, "null": null,
  "number": 123,"string": "Hello World" }]}"""
type Parser = JsonProvider<json>

let parsed = Parser.Load(json)
for table in parsed.Table do
  printfn "%s" table.String

请参阅This documentationthis question

答案 2 :(得分:0)

@Configuration
@EnableWebMvc
public class CorsConfig implements WebMvcConfigurer {

 @Value("#{systemEnvironment['COMPONENT_PARAM_CORS']?:'**'}")
 private String COMPONENT_PARAM_CORS;

 @Override
 public void addCorsMappings(CorsRegistry registry) {
  registry.addMapping("/"+COMPONENT_PARAM_CORS);
 }
}