如何从 Spring Boot 获取操作系统环境变量?

fac*_*off 1 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);
 }
}
Run Code Online (Sandbox Code Playgroud)

导出 COMPONENT_PARAM_CORS=**

打印环境

告诉我它存在,但是当我尝试 mvn clean install 时:发生错误

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}"
Run Code Online (Sandbox Code Playgroud)

然后我的单元测试也下降了(我试图搜索这个错误,但所有主题都是旧的并且使用来自 application.properties 的参数,但我需要使用 env var 而不是 application.properties)

Boh*_*nko 6

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

registry.addMapping("/" + System.getenv("COMPONENT_PARAM_CORS"));
Run Code Online (Sandbox Code Playgroud)

或使用默认值:

registry.addMapping("/" + System.getenv().getOrDefault("COMPONENT_PARAM_CORS", "DEFAULT_VALUE"))
Run Code Online (Sandbox Code Playgroud)

这里有更多信息https://docs.oracle.com/javase/tutorial/essential/environment/env.html

如果你真的想注入变量值,你可以将代码修改为:

@Value("#{systemEnvironment['COMPONENT_PARAM_CORS'] ?: 'DEFAULT_VALUE'}")
private String COMPONENT_PARAM_CORS;
Run Code Online (Sandbox Code Playgroud)