问题
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