So i have a spring 4 application. It contains 3 properties files:
application.properties
application-dev.properties
application-prod.properties
In the header of application.properties, i specify the profile i want:
spring.profiles.active=dev
So in the two other files:
application-dev.properties
application-prod.properties
I have duplicate entries across them, so lets say in the dev file i have:
host=foo
and in prod i have:
host=bar
Spring then picks up the value according to the currently active profile.
In order to tell Spring where the files are, i have a configuration class:
@Configuration
@ComponentScan(basePackages = "my.base.package")
@PropertySource({ "classpath:application.properties", "classpath:application-dev.properties", "classpath:application-prod.properties" })
public class ServiceSpringConfiguration
{
@Bean
public static PropertySourcesPlaceholderConfigurer propertySourcesPlaceholderConfigurer()
{
return new PropertySourcesPlaceholderConfigurer();
}
}
But i have noticed that in this way, Spring loads all properties from all files and will not allow duplicates, and just loads the one you ask for, regardless of the profile. How can i tell Spring to load files according to the selected profile? I would have expect Spring to scan the file name and try to match the profile name....
Btw i refer to the property like so:
@Value("${host}")
private String host;
One easy and simple solution is to use the value of the property 'spring.profiles.active' to load the right application.properties.
In your example, it would be like this :
@Configuration
@ComponentScan(basePackages = "my.base.package")
@PropertySource({ "classpath:application.properties", "classpath:application-${spring.profiles.active}.properties"})
public class ServiceSpringConfiguration
Be aware that this solution comes with a problem because you can have severals active spring profiles and it won't work anymore.
Another solution is to create severals configuration classes by profile :
@Configuration
@Profile('dev')
@PropertySource("classpath:application-dev.properties")
public class Devconfiguration {
}
and
@Configuration
@Profile('prod')
@PropertySource("classpath:application-prod.properties")
public class Prodconfiguration {
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With