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
Nowadays you can put
in your
@Component
,@Bean
, etc., and then access the properties through theEnvironment
class:For a single property in a
@Bean
Another way are the handy
@ConfigurationProperties
beans:Note: Just remember to restart eclipse after setting a new environment variable
Thanks to @Yiling. That was a hint.
After this, you should have one environment variable named 'FILE_PATH'. Make sure you restart your machine after creating that environment variable.
For my use case, I needed to access just the system properties, but provide default values in case they are undefined.
This is how you do it:
Check this article. It gives you several ways to do this, via the
PropertyPlaceholderConfigurer
which supports external properties (via thesystemPropertiesMode
property).You are close :o) Spring 3.0 adds Spring Expression Language. You can use
Combined with
java ... -Denv=QA
should solve your problem.Note also a comment by @yiling:
You can mention your variable attributes in a property file and define environment specific property files like local.properties, production.propertied etc.
Now based on the environment, one of these property file can be read in one the listeners invoked at startup, like the ServletContextListener.
The property file will contain the the environment specific values for various keys.
Sample "local.propeties"
Sample "production.properties"
For using these properties file, you can make use of REsource as mentioned below
SERVER_TYPE can be defined as the environment variable with appropriate values for local and production environment.
With these changes the appplicationContext.xml will have the following changes
Hope this helps .