我有一个 Spring boot Web 应用程序。该应用程序使用 @Configurable 注释通过 java 类进行配置。我介绍了两个配置文件:“安装”、“正常”。 如果安装配置文件处于 Activity 状态,则不会加载任何需要数据库连接的 Bean。 我想创建一个 Controller ,用户可以在其中设置数据库连接参数,完成后我想将 Activity 配置文件从“安装”切换到“正常”并刷新应用程序上下文,这样 Spring 就可以初始化每个需要的 bean数据库数据源。
我可以通过代码修改 Activity 配置文件列表,没有问题,但是当我尝试刷新应用程序上下文时,我得到以下异常:
`java.lang.IllegalStateException:
GenericApplicationContext does not support multiple refresh attempts: just call 'refresh' once`
这就是我启动 Spring Boot 应用程序的方式:
`new SpringApplicationBuilder().sources(MyApp.class)
.profiles("my-profile").build().run(args);`
有谁知道如何启动 spring boot 应用程序,让您多次刷新应用程序上下文?
最佳答案
您不能只刷新现有上下文。您必须关闭旧的并创建一个新的。您可以在此处查看我们如何在 Spring Cloud 中执行此操作:https://github.com/spring-cloud/spring-cloud-commons/blob/master/spring-cloud-context/src/main/java/org/springframework/cloud/context/restart/RestartEndpoint.java .如果你愿意,你可以通过添加 spring-cloud-context 作为依赖项来包含 Endpoint
,或者你可以复制我猜的代码并在你自己的“端点”中使用它。
这是端点实现(字段中缺少一些细节):
@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;
}
关于java - 在 Spring Boot 应用程序中修改 Activity 配置文件并刷新 ApplicationContext 运行时,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28541138/