我有一个 Spring boot Web 应用程序。该应用程序是使用 @Configurable 注释通过 java 类进行配置的。我引入了两个配置文件:“安装”、“正常”。 如果安装配置文件处于 Activity 状态,则不会加载任何需要数据库连接的 Bean。 我想创建一个 Controller ,用户可以在其中设置数据库连接参数,完成后我想将 Activity 配置文件从“安装”切换到“正常”并刷新应用程序上下文,以便 Spring 可以初始化每个需要的 bean DB数据源。
我可以通过代码修改 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 作为依赖项来包含该端点,或者您可以复制我猜的代码并在您自己的“端点”中使用它。
这是端点实现(字段中缺少一些详细信息):
@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/45997776/