修改活动配置文件并刷新Spring Boot应用程序中的ApplicationContext运行时 [英] Modify active profiles and refresh ApplicationContext runtime in a Spring Boot application
问题描述
我有一个Spring Boot Web应用程序.使用 @Configurable 注释通过Java类配置应用程序.我介绍了两个配置文件:安装",正常". 如果安装概要文件处于活动状态,则不会加载任何需要DB连接的Bean. 我想创建一个控制器,用户可以在其中设置数据库连接参数,完成后,我想将活动配置文件从安装"切换为普通"并刷新应用程序上下文,以便Spring可以初始化每个需要的bean数据库数据源.
I have a Spring boot Web application. The application is configured via java classes using the @Configurable annotation. I have introduced two profiles: 'install', 'normal'. If the install profile is active, none of the Beans that require DB connection is loaded. I want to create a controller where the user can set up the db connection parameters and When it's done I want to switch the active profile from 'install' to 'normal' and refresh the application context, so the Spring can init every bean that needs DB data source.
我可以从代码中修改活动配置文件列表,没有问题,但是当我尝试刷新应用程序上下文时,我得到以下例外:
I can modify the list of active profiles from code, without problems, but when i try to refresh the application context, i get the following exception:
`java.lang.IllegalStateException:
GenericApplicationContext does not support multiple refresh attempts: just call 'refresh' once`
这是我启动Spring引导应用程序的方式:
This is how i boot my Spring boot app:
`new SpringApplicationBuilder().sources(MyApp.class)
.profiles("my-profile").build().run(args);`
有人知道如何启动Spring Boot应用程序,让您多次刷新应用程序上下文吗?
Does anybody know how to initiate spring boot app that let's you refresh the app context multiple times ?
推荐答案
您不能只是刷新现有上下文.您必须关闭旧的并创建一个新的.您可以在这里查看我们如何在Spring Cloud中做到这一点:
You can't just refresh an existing context. You have to close the old one and create a new one. You can see how we do it in Spring Cloud here: https://github.com/spring-cloud/spring-cloud-commons/blob/master/spring-cloud-context/src/main/java/org/springframework/cloud/context/restart/RestartEndpoint.java. If you want to you can include that Endpoint
just by adding spring-cloud-context as a dependency, or you can copy the code I guess and use it in your own "endpoint".
这是端点实现(字段中缺少一些详细信息):
Here's the endpoint implementation (some details missing in fields):
@ManagedOperation
public synchronized ConfigurableApplicationContext restart() {
if (this.context != null) {
if (this.integrationShutdown != null) {
this.integrationShutdown.stop(this.timeout);
}
this.application.setEnvironment(this.context.getEnvironment());
this.context.close();
overrideClassLoaderForRestart();
this.context = this.application.run(this.args);
}
return this.context;
}
这篇关于修改活动配置文件并刷新Spring Boot应用程序中的ApplicationContext运行时的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!