Spring Boot Profiles

Spring Boot provides profiles that help to create environment-specific configurations and stereotypes in the applications. Any @Component, @Configuration or @ConfigurationProperties can be marked with @Profile to limit when it is loaded.

@Component
@Profile("dev")
public class ProductsComponent {
// ...
}

Note: You can use an exclamation mark prefix for the profile which means all other profiles except the one that is mentioned. @Profile("!dev")

In addition to that externalized configuration files for each profile can be created containing the related environment properties inside.

Setting Profile

Setting up the spring.profiles.active will specify the active profile of the running instance. This property can be set via different methods in using application properties, command-line, or environment variables.

Command-line: using any of the following commands will help to run the application with dev profile

java -jar -Dspring.profiles.active=dev application.jar
# or
java -jar
application.jar --spring.profiles.active=dev

Environment Variable: setting the following environment will result in using dev as the active profile for the application running on that environment.

export spring_profiles_active=dev

Programmatically: Using ConfigurableEnvironment bean you can set the active profile programmatically.

@Autowired 
private ConfigurableEnvironment env;
...
env.setActiveProfiles("dev");

In Spring boot having an instance of SpringApplication you also can call setAdditionalProfiles("dev")to set the active profile.

SpringApplication app = new SpringApplication(Main.class);
app.setAdditionalProfiles("dev");

Profile Groups

Profile Groups is another feature added in Boot 2.4. using this feature you can have multiple profiles activated under one group of profiles.

spring.profiles.group.development[0]=devdb spring.profiles.group.development[1]=devkafka

The application can now be started using --spring.profiles.active=development to active the development, devdb and devkafka profiles in one hit.

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store