Use Spring to create System properties

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 class="org.springframework.beans.factory.config.MethodInvokingFactoryBean">
    <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!

About these ads

4 thoughts on “Use Spring to create System properties

      1. Thanks for the correction (I corrected my post, I don’t know how I messed up the copy/paste from my application code)
        Yeah WordPress is a bit tedious, you have to use the tag: <pre> around your code to keep your tags

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s