How to switch spring profile at runtime

无人久伴 提交于 2019-12-24 18:34:54

问题


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

}

回答1:


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.



来源:https://stackoverflow.com/questions/48570314/how-to-switch-spring-profile-at-runtime

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!