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

SaW*_*aWo 8 java refresh applicationcontext spring-profiles spring-boot

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

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

`java.lang.IllegalStateException:
 GenericApplicationContext does not support multiple refresh attempts: just call 'refresh' once`
Run Code Online (Sandbox Code Playgroud)

这是我启动Spring启动应用程序的方式:

`new SpringApplicationBuilder().sources(MyApp.class)
.profiles("my-profile").build().run(args);` 
Run Code Online (Sandbox Code Playgroud)

有没有人知道如何启动春季启动应用程序让你多次刷新应用程序上下文?

Dav*_*yer 13

您不能只刷新现有的上下文.你必须关闭旧的并创建一个新的.您可以在此处查看我们如何在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.如果你愿意,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;
}
Run Code Online (Sandbox Code Playgroud)