3

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)

3 Answers 3

9

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;
Sign up to request clarification or add additional context in comments.

4 Comments

I know about System.getenv(), but it work when app is compiled, but I need to receive params when I run application, or @value also precompiled?
Both System.getenv() and SPEL expression within @Value will be executed at runtime, not compile time, so both options should work for you.
And I can use default value like :
For default value you can use argumentless System.getenv() call which gives you a Map<String, String>. Then call getOrDefault(key, defaultValue) method (java 1.8+). And for SPEL option just use elvis operator: ?:. I have adjusted my answer to show this.
1

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.

Comments

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);
 }
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.