如何在运行时切换弹簧轮廓 [英] How to switch spring profile at runtime
本文介绍了如何在运行时切换弹簧轮廓的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有带有配置文件的spring boot应用程序.现在,我想在运行时切换配置文件,刷新spring上下文并继续执行应用程序.如何在运行时切换活动配置文件(switchEnvironment方法)?
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
Config.class
@Configuration
@ConfigurationProperties
public class Config{
@Autowired
private ConfigurableEnvironment env;
public ConfigurableEnvironment getEnv() {
return env;
}
public void setEnv(ConfigurableEnvironment env) {
this.env = env;
}
}
推荐答案
所有您需要的东西,都会将此方法添加到您的主类中,并创建Controller或Service来调用此方法.
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();
}
}
控制器:
@RestController
public class RestartController {
@PostMapping("/restart")
public void restart() {
Application.restart();
}
}
这篇关于如何在运行时切换弹簧轮廓的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文