Spring Boot set Active Profile by code change

May 25, 2020 | No comments

Setting and Reading Active Profiles

This article shows different ways to set the active profile that requires java code change. We can then activate different profiles in different environments based on some application logics. Also, we can list the list of active profiles as shown in the below examples. The article is divided into two sections, one for setting the active profile and the other one is listing the active profiles.

Setting though setAdditionalProfiles.

The following example shows how to set the active profile "prod" by calling setAdditionalProfiles from the Spring Application Class. We need to set the profiles before the run method.
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.ComponentScan;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

@ComponentScan({"com.bootng", "com.bootng.service"})
public class RestApplication {

  private static final Logger log = LoggerFactory.getLogger(RestApplication.class);

  public static void main(String args[]) {
    log.info("about to call RestApplication.run()");

    // set extra profile
    SpringApplication application = new SpringApplication(RestApplication.class);
    log.info("completed executing RestApplication.run()");

Listing Active Spring Boot Profiles by @Value

the property spring.profiles.active contains the list of active profiles. We can read this value by @Value annotations

Listing Active Spring Boot Profiles by Environment

Through org.springframework.core.env.Environment
The following code shows how to read the list of active profiles by using org.springframework.core.env.Environment object.
private Environment environment;

//read the active profiles from environment object.
String result = "Currently active profile - ";
for (String profileName : environment.getActiveProfiles()) {
    result+=" " + profileName;


No comments :

Post a Comment

Please leave your message queries or suggetions.