how to read System environment variable in Spring applicationContext
How to read the system environment variable in the application context?
I want something like :
<util:properties id="dbProperties"
location="classpath:config_DEV/db.properties" />
or
<util:properties id="dbProperties"
location="classpath:config_QA/db.properties" />
depending on the environement.
Can I have something like this in my application Context?
<util:properties id="dbProperties"
location="classpath:config_${systemProperties.env}/db.properties" />
where the actual val is set based on the SYSTEM ENVIRONMENT VARIABLE
I'm using Spring 3.0
Solution 1:
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']}
Solution 2:
Nowadays you can put
@Autowired
private 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 default
Integer 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
}
@Component
public class MyOtherBean {
@Autowired
MyProperties myProperties;
}
Note: Just remember to restart eclipse after setting a new environment variable
Solution 3:
Check this article. It gives you several ways to do this, via the PropertyPlaceholderConfigurer
which supports external properties (via the systemPropertiesMode
property).