how to read System environment variable in Spring applicationContext how to read System environment variable in Spring applicationContext java java

how to read System environment variable in Spring applicationContext


You are close :o)Spring 3.0 adds Spring Expression Language. You can use

<util:properties id="dbProperties"     location="classpath:config_#{systemProperties['env']}/db.properties" />

Combined with java ... -Denv=QA should solve your problem.

Note also a comment by @yiling:

In order to access system environment variable, that is OS level variables as amoe commented, we can simply use "systemEnvironment" instead of "systemProperties" in that EL. Like #{systemEnvironment['ENV_VARIABLE_NAME']}


Nowadays you can put

@Autowiredprivate Environment environment;

in your @Component, @Bean, etc., and then access the properties through the Environment class:

environment.getProperty("myProp");

For a single property in a @Bean

@Value("${my.another.property:123}") // value after ':' is the defaultInteger property;

Another way are the handy @ConfigurationProperties beans:

@ConfigurationProperties(prefix="my.properties.prefix")public class MyProperties {  // value from my.properties.prefix.myProperty will be bound to this variable  String myProperty;  // and this will even throw a startup exception if the property is not found  @javax.validation.constraints.NotNull  String myRequiredProperty;  //getters}@Componentpublic class MyOtherBean {  @Autowired  MyProperties myProperties;}

Note: Just remember to restart eclipse after setting a new environment variable


Check this article. It gives you several ways to do this, via the PropertyPlaceholderConfigurer which supports external properties (via the systemPropertiesMode property).