[英]How to get OS environment variable from Spring Boot?
I am novice to java and spring framework.我是java和spring框架的新手。 My questions is how to inject OS(ubuntu) environment variable to spring boot bean.我的问题是如何将 OS(ubuntu) 环境变量注入 spring boot bean。 What I tried:我试过的:
@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);
}
}
export COMPONENT_PARAM_CORS=**导出 COMPONENT_PARAM_CORS=**
printenv打印环境
says me that its present, but when I try to mvn clean install: error occured告诉我它存在,但是当我尝试 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}"
and then my unit test also droped (I am trying to search this error, but all topics is old and uses params from application.properties, but I need to use env var not application.properties)然后我的单元测试也下降了(我试图搜索这个错误,但所有主题都是旧的并且使用来自 application.properties 的参数,但我需要使用 env var 而不是 application.properties)
You can use System.getenv(<environment name>)
method to retrieve an environment variable value.您可以使用System.getenv(<environment name>)
方法来检索环境变量值。 Like:喜欢:
registry.addMapping("/" + System.getenv("COMPONENT_PARAM_CORS"));
or with default value:或使用默认值:
registry.addMapping("/" + System.getenv().getOrDefault("COMPONENT_PARAM_CORS", "DEFAULT_VALUE"))
More information here https://docs.oracle.com/javase/tutorial/essential/environment/env.html这里有更多信息https://docs.oracle.com/javase/tutorial/essential/environment/env.html
If you really want to inject variable value you can modify your code to something like:如果你真的想注入变量值,你可以将代码修改为:
@Value("#{systemEnvironment['COMPONENT_PARAM_CORS'] ?: 'DEFAULT_VALUE'}")
private String COMPONENT_PARAM_CORS;
You should use System.getenv() , for example:您应该使用System.getenv() ,例如:
import java.util.Map;
public class EnvMap {
public static void main (String[] args) {
Map<String, String> env = System.getenv();
for (String envName : env.keySet()) {
System.out.format("%s=%s%n",
envName,
env.get(envName));
}
}
}
Please refer to This documentation and this question .请参阅此文档和此问题。
@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);
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.