Spring Profiles

Spring profile is a way to achieve environment specific execution of class or code i.e. Spring Profiles provide a way to segregate parts of your application configuration and make it be available only in certain environments.  If you want to run your piece of code or initialize any specific bean in any certain environment, Spring Profiles is the option.


Any class marked with @Component or @Configuration, can also be marked @Profile in Spring application, as shown in the following example

public class ProductionConfiguration {
// ...

As you can notice, the above bean is marked with production profile. i.e. if we mark our production profile active then only the ProductionConfiguration bean will be initialized otherwise it won’t.

Setting Profile

The above mentioned profile can be marked active with below configuration.

  • In application.properties or application.yml
  • In command line by using the following switch

  • Programmatically via ConfigurableEnvironment
private static ConfigurableEnvironment env;
public static void main(String[] args) {
    SpringApplication.run(TektutorialSpringProfileApplication.class, args);
  • Programmatically via SpringApplication
    The SpringApplication entry point also has a Java API for setting additional profiles (that is, on top of those activated by the spring.profiles.active property).
public static void main(String[] args) {
         SpringApplication obj = new SpringApplication(TektutorialSpringProfileApplication.class);
         obj.setAdditionalProfiles("profile1", "profile2");
         obj.run(TektutorialSpringProfileApplication.class, args);
  • Maven profile

Adding Active Profiles

We can specify default active profiles in application.properties and then replace them by using the command line switch. Command line inputs always override default properties mention in application.properteis.

The spring.profiles.include property can be used to unconditionally add active profiles in application.properties. Like below

spring.profiles: prod
- proddb
- prodmq

Lets Code

Lets create one simple spring boot application to show what we saw above.

I have created my application from
https://start.spring.io/ keeping only web as starter and the folder structure looks like below.

Overall folder structure of project

application.properties with profile UAT
Console output with Profile UAT
application.properties with profile DEV
Console output with Profile DEV

The above code can be found at the repo

Hope this must have cleared your doubts about Spring Profile. Thanks for reading.