Tuesday, March 18, 2014

Environment variables and property placeholders using Spring and Tomcat

I've recently been playing on my server and then decided to remove my properties from the code. Even though I still have my properties file managed by Spring's property placeholder, I'm now using the system-properties-mode="OVERRIDE" which allows me to override the values using environment variables. It's very useful in case there are properties you want to remove from your .war (like passwords)

As I'm using Tomcat, the easiest way I found to set it was to use the setenv.sh configuration file. Just create it in Tomcat's bin file and it will be automatically read and used.

Here's an example:

spring.xml
<context:property-placeholder location="classpath:/database.properties" ignore-unresolvable="true" system-properties-mode="OVERRIDE"/>
setenv.sh
JAVA_OPTS="$JAVA_OPTS -Dmongo.db.host=<host> -Dmongo.db.port=<port> -Dmongo.db.name=<db_value> -Dmongo.db.username=<user> -Dmongo.db.password=<pwd>"
Obs: the file should be named setenv.bat on Windows

To test if it worked, after starting your Tomcat, use:
 ps aux | grep -i tomcat
You should be able to see your environments variable set!

No comments:

Post a Comment