How to load property file based on spring profiles
For Spring Boot applications it will work easily even by using a YAML File
spring:
profiles: dev
property: this is a dev env
---
spring:
profiles: prod
property: this is a production env
---
However, for a Spring MVC application, it needs more work. Have a look at this link
Basically, it involves 2 steps
- Get the Spring Profile within servlet context
If you have set the profile on the server and want it to retrieve it within your application you can use System.getProperty or System.getenv methods. Here is the code which fetches the profile and defaults it to a local profile, if no profile has been found.
private static final String SPRING_PROFILES_ACTIVE = "SPRING_PROFILES_ACTIVE";
String profile;
/**
* In local system getProperty() returns the profile correctly, however in docker getenv() return profile correctly
* */
protected void setSpringProfile(ServletContext servletContext) {
if(null!= System.getenv(SPRING_PROFILES_ACTIVE)){
profile=System.getenv(SPRING_PROFILES_ACTIVE);
}else if(null!= System.getProperty(SPRING_PROFILES_ACTIVE)){
profile=System.getProperty(SPRING_PROFILES_ACTIVE);
}else{
profile="local";
}
log.info("***** Profile configured is ****** "+ profile);
servletContext.setInitParameter("spring.profiles.active", profile);
}
- To access the application-dev.properties, say now you will need to use @Profile("dev") at the class level
The following code will fetch the application-dev.properties and common.properties
@Configuration
@Profile("dev")
public class DevPropertyReader {
@Bean
public static PropertyPlaceholderConfigurer properties() {
PropertyPlaceholderConfigurer ppc = new PropertyPlaceholderConfigurer();
Resource[] resources = new ClassPathResource[] { new ClassPathResource("properties/common.properties"), new ClassPathResource("properties/application-dev.properties") };
ppc.setLocations(resources);
ppc.setIgnoreUnresolvablePlaceholders(true);
return ppc;
}
}
For accessing say application-prod.properties you have to use @Profile("prod")
at the class level. More details can be found here
Put property file in same location as application.property
and follow
the naming convention application-{profile}.properties
like
application-dev.properties
,application-test.properties
,
application-prod.properties
And in application.properties
set spring.profiles.active=dev,test
etc
I'll give step by step procedure for Spring boot applications.
- Inside /src/main/resources/application.properties mention spring.profiles.active=dev (or Prod)
- Create /src/main/resources/application-dev.properties and give your custom dev configurations here.
- Create /src/main/resources/application-prod.properties and give your custom prod configurations here.
Run.