[英]How to switch spring profile at runtime
I have spring boot application with profiles.我有带有配置文件的 Spring Boot 应用程序。 Now I want to switch profile at runtime, refresh spring context and continue application execution.
现在我想在运行时切换配置文件,刷新 spring 上下文并继续执行应用程序。 How to switch active profile at runtime (switchEnvironment method)?
如何在运行时切换活动配置文件(switchEnvironment 方法)?
@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).为了详细说明其他一些答案,这就是 Netflix Archaius ( https://github.com/Netflix/archaius/wiki ) 之类的工具试图解决的问题(动态上下文配置)。 As far as I'm aware, the only way to accomplish this would be to refresh the contexts by restarting the application.
据我所知,完成此操作的唯一方法是通过重新启动应用程序来刷新上下文。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.