Aleksei
Aleksei

Reputation: 137

How to switch spring profile at runtime

I have spring boot application with profiles. Now I want to switch profile at runtime, refresh spring context and continue application execution. How to switch active profile at runtime (switchEnvironment method)?

@SpringBootApplication
public class Application implements CommandLineRunner {

    @Autowired
    private Config config;

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

    @Override
    public void run(String ... strings) throws Exception {
        System.out.printf("Application is running in %s environment, service parameters below:\n",
                getEnvProperty("spring.profiles.active").toUpperCase());
        printServiceParameters();
        switchEnvironment();
        printServiceParameters();
    }

    private String getEnvProperty(String propertyName) {
        return config.getEnv().getProperty(propertyName);
    }

    private void printServiceParameters() {
        System.out.println(getEnvProperty("service.endpoint"));
    }

    private void switchEnvironment() {
        //todo Switch active profile
    }

}

Config.class

@Configuration
@ConfigurationProperties
public class Config{

    @Autowired
    private ConfigurableEnvironment env;

    public ConfigurableEnvironment getEnv() {
        return env;
    }

    public void setEnv(ConfigurableEnvironment env) {
        this.env = env;
    }

}

Upvotes: 8

Views: 18333

Answers (2)

Nikolay  Gribanov
Nikolay Gribanov

Reputation: 146

All what you need, it's add this method into your main class, and create Controller or Service for call this method.

@SpringBootApplication
public class Application {

    private static ConfigurableApplicationContext context;

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

    public static void restart() {

        Thread thread = new Thread(() -> {
            context.close();
            context = SpringApplication.run(Application.class, "--spring.profiles.active=your_profile");
        });

        thread.setDaemon(false);
        thread.start();
    }

}

Controller:

@RestController
public class RestartController {

    @PostMapping("/restart")
    public void restart() {
        Application.restart();
    }
}

Upvotes: 13

Shane Burroughs
Shane Burroughs

Reputation: 111

To elaborate on some of the other answers, this is what tools like Netflix Archaius (https://github.com/Netflix/archaius/wiki) attempt to solve (Dynamic Context Configurations). As far as I'm aware, the only way to accomplish this would be to refresh the contexts by restarting the application.

Upvotes: 2

Related Questions