Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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;
    }

}
like image 397
Aleksei Avatar asked May 15 '26 15:05

Aleksei


2 Answers

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();
    }
}
like image 95
Nikolay Gribanov Avatar answered May 17 '26 14:05

Nikolay Gribanov


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.

like image 40
Shane Burroughs Avatar answered May 17 '26 13:05

Shane Burroughs