简体   繁体   中英

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

}

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM