1

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)

Sh. Pavel
  • 1,584
  • 15
  • 28
faceoff
  • 151
  • 3
  • 12

3 Answers3

6

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;
Bohdan Levchenko
  • 3,411
  • 2
  • 24
  • 28
  • 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? – faceoff Jul 10 '18 at 10:53
  • Both `System.getenv()` and SPEL expression within `@Value` will be executed at runtime, not compile time, so both options should work for you. – Bohdan Levchenko Jul 10 '18 at 10:57
  • And I can use default value like : – faceoff Jul 10 '18 at 18:27
  • For default value you can use argumentless `System.getenv()` call which gives you a `Map`. 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. – Bohdan Levchenko Jul 11 '18 at 10:11
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.

agrim khanna
  • 105
  • 1
  • 9
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);
 }
}
faceoff
  • 151
  • 3
  • 12