I'm a Lead engineer at Terracotta, Software AG. I have 10+ years of experience with Java, but I also speak other languages, C, C++, Javascript, Coffeescript, PHP, Perl... See my blog to know about my different personal projects! Aurelien is a DZone MVB and is not an employee of DZone and has posted 17 posts at DZone. You can read more from them at their website. View Full User Profile

Use Spring to create System properties

12.11.2011
| 11064 views |
  • submit to reddit

That’s an old trick, but it helped me today, and I’m pretty sure I’ll use it again.

You can setup some System properties with Spring.
Mix that with Maven resources filtering and you can execute your application with some specific System properties according to your profile.

In your applicationContext.xml, add:

 <bean>
    <property name="targetClass" value="java.lang.System"/>
    <property name="targetMethod" value="setProperty"/>
    <property name="arguments">
      <list>
        <value>logsDir</value>
        <value>${logs.dir}</value>
      </list>
    </property>
  </bean>

Here ${logs.dir} is replaced before the execution of the application. During the build phase, maven will look at the properties you’ll have defined in your profile, and use them to filter the files you will have set (in this example, we set maven to filter all files in src/main/resources, where applicationContext.xml is located.

For instance, we can define a property: logs.dir=/mydevmachine/logs for a dev profile, and logs.dir=/myprodmachine/logs for a prod profile.

Then in your application, doing a System.getProperty(“logsDir”) will give you the correct value according to your maven profile.

No need to add System properties to MAVEN_OPTS anymore!

From http://jsoftbiz.wordpress.com/2011/12/08/use-spring-to-create-system-properties/

Published at DZone with permission of Aurelien Broszniowski, author and DZone MVB.

(Note: Opinions expressed in this article and its replies are the opinions of their respective authors and not those of DZone, Inc.)

Tags: