Alex Rivera | Logout

Load environment-specific properties for use with PropertyPlaceholderConfigurer?

Asked 2010-02-05T03:47:54.697
32

This seems like a pretty common problem, but I haven't found any sort of consensus on the best method, so I'm posing the question here.

I'm working on a command-line Java application using Spring Batch and Spring. I'm using a properties file along with a PropertyPlaceholderConfigurer, but I'm a little unsure of the best way of handling the properties files for multiple environments (dev, test, etc.). My Googling is only turning up programmatic ways of loading the properties (i.e., in the Java code itself), which doesn't work for what I'm doing.

One approach I've considered is simply placing each environment's properties file on the server and adding the file's directory to the classpath via a command-line argument, but I've been having trouble loading the file using that method.

The other method I'm considering is to just include all the properties files in the jar and use a system property or command line argument to fill in the name of the properties file at runtime, like this:

<bean id="propertyConfigurer"
    class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
    <property name="locations">
        <list>
            <value>classpath:job.properties.${env}</value>
        </list>
    </property>
</bean>

I lean towards the latter solution, but I'm also looking to see if there's a better method I'm overlooking.

I should also mention that I have to make the substitution at runtime rather than in the build. The process I'm constrained to use requires a single build which will be promoted through the environments to production, so I'm unable to use substitution ala Maven or Ant.

Edit
Report

1 Answer

8

You could use <context:property-placeholder location="classpath:${target_env}configuration.properties" /> in your Spring XML and configure ${target_env} using a command-line argument (-Dtarget_env=test.).

Starting in Spring 3.1 you could use <context:property-placeholder location="classpath:${target_env:prod.}configuration.properties" /> and specify a default value, thereby eliminating the need to set the value on the command-line.

In case Maven IS an option, the Spring variable could be set during plugin execution, e.g. during test or integration test execution.

<plugin>
    <groupId>org.apache.maven.plugins</groupId>
    <artifactId>maven-surefire-plugin</artifactId>
    <version>2.12</version>
    <configuration>
        <systemPropertyVariables>
            <target_env>test.</target_env>
        </systemPropertyVariables>
    </configuration>
</plugin>

I assume different Maven profiles would also work.

answered 2012-07-20T14:39:13.933

Your Answer