在Spring Boot应用程序中修改活动概要文件并刷新ApplicationContext运行时



我有一个Spring启动Web应用程序。该应用程序是通过使用@Configuration注释的java类进行配置的。我介绍了两个配置文件:"安装"one_answers"正常"。如果安装概要文件处于活动状态,则不会加载任何需要DB连接的Bean。我想创建一个控制器,用户可以在其中设置数据库连接参数,完成后,我想将活动配置文件从"install"切换到"normal",并刷新应用程序上下文,这样Spring就可以初始化每个需要数据库数据源的bean。

我可以从代码中修改活动配置文件的列表,没有问题,但当我尝试刷新应用程序上下文时,我会得到以下异常

`java.lang.IllegalStateException:
 GenericApplicationContext does not support multiple refresh attempts: just call 'refresh' once`

这就是我如何启动我的春季启动应用程序:

`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上下文作为依赖项来包含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;
}

最新更新