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

标签 java spring-boot refresh applicationcontext spring-profiles

我有一个 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/

相关文章:

java - 如何在不写入输出流的情况下从 ZipInputStream 获取每个 ZipFile 条目的字节/内容?

java - 如何在Android上的fragment中使用onBackPress按钮

java - 将 JUnit 测试动态添加到测试类

java - 如何使用Spring以只读和读写方式进行数据库路由

java - 手动添加 spring-boot-starter-thymeleaf

spring - 更改 'spring.jpa.hibernate.ddl-auto' 的值后重新启动 Spring Boot 应用程序时,我的表数据被删除

Android ICS ListView 刷新问题

android - 当用户正在使用应用程序时,在后台线程中获取有关布局刷新/更改的通知

java - 瓦丁 7 : What is the simplest way to refresh a Vaadin View in 5 minute intervals?

java - 在 Java 中解析算术表达式并从中构建树