Reputation: 191
I am novice to java and spring framework. My questions is how to inject OS(ubuntu) environment variable to 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=**
printenv
says me that its present, but when I try to mvn clean install: error occured
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)
Upvotes: 3
Views: 11582
Reputation: 191
@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);
}
}
Upvotes: 0
Reputation: 3561
You can use System.getenv(<environment name>)
method to retrieve an environment variable value. 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
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;
Upvotes: 9
Reputation: 105
You should use System.getenv(), for example:
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.
Upvotes: 1