Load properties file in Spring depending on profile

java, spring

Solution

I have decided to submit and answer to this as it has not yet been accepted. It may not be what you are looking for specifically but it works for me. Also note that i am using the new annotation driven configuration however it can be ported to the xml config.

I have a properties file for each environment(dev.properties, test.properties etc)

I then have a RootConfig class that is the class that is used for all the configuration. All that this class has in it is two annotations: @Configuration and @ComponentScan(basePackageClasses=RootConfig.class). This tells it to scan for anything in the same package as it.

There is then a Configuration Containing all my normal configuration sitting wherever. There is also a configuration for each environment in the same package as the root configuration class above.

The environment specific configurations are simply marker classes that have the following annotations to point it to the environment specific properties files:

@Configuration
@PropertySource("classpath:dev.properties")
@Import(NormalConfig.class)
@Profile("dev")

The import tells it to bring in the normal config class. But when it gets in there it will have the environment specific properties set.

Problem

I have a Spring 3.1 application. Let's say it has an XML with the following content: ``` <context:property-placeholder location="classpath:somename.properties" /> <context:property-placeholder location="classpath:xxx.properties" /> ``` I would like some.properties to be always loaded (let's assume it exists), but the xxx part of the second place holder to be replaced by some name depending on the active profile. I've tried with this: ``` <beans profile="xx1"> <context:property-placeholder location="classpath:xx1.properties" /> </beans> <beans profile="xx2"> <context:property-placeholder location="classpath:xx2.properties" /> </beans> ``` Also, both files have properties with the same key but different value. But it didn't work as some later bean that has a placeholder for one property whose key is defined in xx1.properties (and xx2.properties) makes Spring complain that the key is not found in the application context.

Original source