How to force spring to have exactly one active profile?

1k Views Asked by At

I am trying to have one, exactly one profile active on my SpringBoot application. I used to override the configureProfiles method, so if more than one profiles where active the application did not run. In case no profile was active, I added a default profile. The profile I wanted to be active has to be defined using SPRING_PROFILES_ACTIVE environmental variable.

With the last versions (2.5.x) of SpringBoot configureProfiles is empty and when called, the active profile defined using SPRING_PROFILES_ACTIVE is not even loaded.

Any idea how I can have exactly one (no more, no less) profile active on SpringBoot?

2

There are 2 best solutions below

0
On

Have you tried to set the active profile ?

private ConfigurableEnvironment env;
...
env.setActiveProfiles(SPRING_PROFILES_ACTIVE);

There are many ways to set your profile.

You can check : this Spring profiles tutorial

Or this post

1
On

The SPRING_PROFILES_ACTIVE environment variable, will actually set the active profile(s).

If you want to get the active profiles just add the Environment to your @SpringBootApplication class and raise any kind of Exception or shut down the application in case of multiple profiles have been set up.

See below a naive implementation.

import javax.annotation.PostConstruct;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.ApplicationContext;
import org.springframework.core.env.Environment;

@SpringBootApplication
public class SpringDemoApplication {

    private Environment environment;

    public static void main(String[] args) {
        SpringApplication.run(SpringDemoApplication.class, args);
    }

    public SpringDemoApplication(Environment environment) {
        this.environment = environment;
    }

    @PostConstruct
    private void post() {
        if (!this.isThereJustOneActiveProfile()) {
            throw new RuntimeException("You must set just one profile.");
        }
    }

    private boolean isThereJustOneActiveProfile() {
        return (this.environment.getActiveProfiles().length == 1);
    }
}