1. Overview

Thia article is about spring boot set active profile programmatically or we can set how to set active profile at runtime in spring boot application. Based on active profiles spring boot will load beans and configurations. Here is an article for spring boot profile example.

org.springframework.boot.SpringApplication has method setAdditionalProfiles which accepts the Array of addition active profiles. We can set profiles using JVM arguments like -Dspring.profiles.active=production in command line. setAdditionalProfiles method will add more profiles but make sure that we can add more profiles only before application start or runs. We can set active profile based on conditions at runtime using setAdditionalProfiles method.

After setting active profile programmatically, We can check or get active profiles in spring boot using this article.

2. Example

package com.javadeveloperzone;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.ComponentScan;

/**
 * Created by JavaDeveloperZone on 28-04-2017.
 * Spring boot set active profile at run time or programmatically
 */

@SpringBootApplication
@ComponentScan // Using a root package also allows the @ComponentScan annotation to be used without needing to specify a basePackage attribute
public class SpringBootConfig {
    public static void main(String[] args) throws Exception {
        SpringApplication springApplication=new SpringApplication(SpringBootConfig.class);
        String[] profiles= new String[]{"production","production-extra"}; // array of profiles, create array of one profile in case single profile
        springApplication.setAdditionalProfiles(profiles); // set active profile, We can write condition here based on requirements
        springApplication.run(args);  // run spring boot application
    }
}

Output:

In console log, We can see all active profiles.

2018-04-28 17:34:47.564  INFO 123928 --- [           main] com.javadeveloperzone.SpringBootConfig   : The following profiles are active: production,production-extra
2018-04-28 17:34:47.650  INFO 123928 --- [           main] ationConfigEmbeddedWebApplicationContext : Refreshing org.springframework.boot.context.embedded

3. References

Was this post helpful?
Let us know, if you liked the post. Only in this way, we can improve us.
Yes
No

Leave a Reply

Your email address will not be published. Required fields are marked *