This tutorial will describe how to use profiles to manage loading of properties file in Spring Boot.
Abstract
Spring Boot has been getting quite popular for Microservices development for good reasons. While Spring was known to reduce boilerplate code, Spring Boot has gone even further with its convention over configuration approach.
Spring Boot has made it very easy to handle profile specific configuration parameters and implementations. Profiles may represent your environments such as dev, test, staging, prod etc. or may help you with different deployments of same service for different business/entities.
Profile specific Configuration files
Spring Boot, irrespective of active profile, always load application.properties or application.yml file if present.
After this, Spring Boot will load file with name application-{profile}.properties or application-{profile}.yml. In case, more than one active profiles are active, it will load all the files with those profiles one by one.
E.g. if dev and finance profiles are active, Spring Boot will load following files -
- application.properties
- application-dev.properties
- application-finance.properties
Please note that loaded files override properties with same keys from previously loaded files.
Profile specific Spring Bean
Likewise, we may also need profile specific Spring beans loading.
For instance, we have an interface TutorialsService with two implementations RemoteTutorialsService and FileBasedTutorialsService. We intend to use RemoteTutorialsService in staging/production env and FileBasedTutorialsService in dev/test env.
In order to configure it in such way, we can annotate these classes with @Profile annotation -
@Service
@Profile({"dev", "test"})
public class FileBasedTutorialsService implements TutorialsService {
@Service
@Profile({"staging", "prod"})
public class RemoteTutorialsService implements TutorialsService {
Alternatively, if you are using a central Java configuration file for Spring, you can use @Profile annoation with @Bean annoations as shown below -
@Bean
@Profile({"dev", "test"})
public FileBasedTutorialsService fileBasedTutorialsService() {
return new FileBasedTutorialsService();
}
@Bean
@Profile({"staging", "prod"})
public RemoteTutorialsService remoteTutorialsService() {
return new RemoteTutorialsService();
}
Setting Active Profiles
Active profiles can be set in Spring Boot applications by adding comma separated list of profiles to system property spring.profiles.active.
E.g. following is configuration to activate dev and finance profiles-
spring.profiles.active=dev,finance
Thank you for reading through the tutorial. In case of any feedback/questions/concerns, you can communicate same to us through your comments and we shall get back to you as soon as possible.