小编典典

修改活动配置文件并刷新Spring Boot应用程序中的ApplicationContext运行时

spring-boot

我有一个Spring Boot Web应用程序。使用 @Configurable
批注通过Java类配置应用程序。我介绍了两个配置文件:“安装”,“正常”。如果安装概要文件处于活动状态,则不会加载任何需要DB连接的Bean。我想创建一个控制器,用户可以在其中设置数据库连接参数,完成后,我想将活动配置文件从“安装”切换为“普通”并刷新应用程序上下文,以便Spring可以初始化每个需要的bean
DB数据源。

我可以通过代码修改活动配置文件列表,没有问题,但是当我尝试刷新应用程序上下文时,出现以下 异常

`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应用程序,让您多次刷新应用程序上下文吗?


阅读 421

收藏
2020-05-30

共1个答案

小编典典

您不能只是刷新现有上下文。您必须关闭旧的并创建一个新的。您可以在这里查看我们如何在Spring
Cloud中做到这一点:[https](https://github.com/spring-cloud/spring-cloud-
commons/blob/master/spring-cloud-
context/src/main/java/org/springframework/cloud/context/restart/RestartEndpoint.java)
//github.com/spring-cloud/spring-cloud-commons/blob/master/spring-cloud-
context/src/main/java/org/springframework/ cloud / context / restart /
RestartEndpoint.java。如果您愿意,可以Endpoint仅通过添加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;
}
2020-05-30