Alex Rivera | Logout

Import Spring config file based on property in .properties file

Asked 2009-10-05T13:24:46.747
34

In my Spring xml configuration I'm trying to get something like this to work:

<beans>

   <import resource="${file.to.import}" />

   <!-- Other bean definitions -->

</beans>

I want to decide which file to import based on a property in a properties file. I know that I can use a System property, but I can't add a property to the JVM at startup.

Note: The PropertyPlaceHolderConfigurer will not work. Imports are resolved before any BeanFactoryPostProcessors are run. The import element can only resolve System.properties.

Does anyone have a simple solution to this? I don't want to start subclassing framework classes and so on...

Thanks

Edit
Report

3 Answers

6

For the Spring 2.5 and 3.0, I have a similar solution to louis, however I've just read about 3.1's upcoming feature: property management, which sounds great too.

answered 2011-03-02T23:26:51.433
1

Add something similar to the following:

<bean id="propertyConfigurer" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
    <property name="ignoreResourceNotFound"><value>true</value></property>
    <property name="locations">
        <list>
            <value>classpath:propertyfile.properties</value>
        </list>
    </property>
</bean>
answered 2009-10-05T19:09:55.350
0

André Schuster's answer, which I bumped, helped me solve a very similar issue I was having in wanting to find a different expression of properties depending on whether I was running on my own host, by Jenkins on our build host or in "real" deployment. I did this:

<context:property-placeholder location="file:///etc/myplace/database.properties" />

followed later by

<bean id="propertyConfigurer"
      class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
    <property name="locations">
        <list>
            <value>WEB-INF/classes/resources/database.properties</value>
            ...
        </list>
    </property>
</bean>

which solved my problem because on my development host, I put a link to my own copy of database.properties in /etc/myplace/database.properties, and a slightly different one on the server running Jenkins. In real deployment, no such file is found, so Spring falls back on the "real" one in resources in my class files subdirectory. If the properties in question have already been specified by the file on /etc/myplace/database.properties, then (fortunately) they aren't redefined by the local file.

answered 2012-02-28T18:25:14.980

Your Answer