James
James

Reputation: 1780

Is it possible to specify a context property placeholder at runtime

I have a standalone jar that uses spring. The config in my spring xml uses placeholders of which I've been replacing when compiling with maven. Example spring config:

<bean id="foo" class="package.Foo">
    <property name="host" value="${db.host}" />
</bean>

Instead of replacing ${db.host} using maven I'd like to pass in a properties file at runtime, e.g.

java -jar Application.jar productionDB.properties

This would allow me to switch the db host at runtime by passing in the production db properties file or the testing db properties file.

Is it possible to do this or are there any better ways of achieving the same goal?

Upvotes: 2

Views: 3865

Answers (4)

NullPointerException
NullPointerException

Reputation: 3804

You can pass the values using the context:property-placeholder. So your setup would be something like:

<context:property-placeholder location="file://opt/db.properties"/>

Then when you are wiring up your Foo service, you can use the property names in your config, such as

<bean id="foo" class="package.Foo">
   <property name="host" value="${db.host}" />
</bean>

Then just use the different set of files for each environmnet

See the spring docs for more details.

Upvotes: 0

Jonathan
Jonathan

Reputation: 20375

You could specify your property file as a System Property, e.g.:

java -jar Application.jar -DappConfig=/path/to/productionDB.properties

Then you should be able to reference that in your application context:

<context:property-placeholder location="file:${appConfig}"/>

<bean id="foo" class="package.Foo">
    <property name="host" value="${db.host}" />
</bean>

Upvotes: 3

ach
ach

Reputation: 6234

There are a few options:

  1. Set your resources via your container's JNDI and use Spring's <jee:jndi-lookup/>.
  2. Use Spring's <context:property-placeholder location="classpath:/myProps.properties" />. I prefer this short-hand over the "full" bean definition because Spring will automatically use the correct implementation (PropertyPlaceholderConfigurer for Spring < 3.1, or PropertySourcesPlaceholderConfigurer for Spring 3.1+). Using this configuration, you would just drop the myProps.properties at the root of your classpath (${TOMCAT_HOME}/lib for example).

Upvotes: 0

flash
flash

Reputation: 6810

You could use a PropertyPlaceholderConfigurer to use a .properties file to pass in the required variables.

<bean id="placeholderConfig"
    class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
    <property name="locations">
        <list>
            <value>classpath:productionDB.properties</value>
        </list>
    </property>
</bean>

You can leave your bean declaration as is. The properties will be automatically taken from the productionDB.properties file.

Upvotes: 1

Related Questions