Modify active profiles and refresh ApplicationContext runtime in a Spring Boot application

帅比萌擦擦* 提交于 2019-12-18 05:55:53

问题


I have a Spring boot Web application. The application is configured via java classes using the @Configurable annotation. I have introduced two profiles: 'install', 'normal'. If the install profile is active, none of the Beans that require DB connection is loaded. I want to create a controller where the user can set up the db connection parameters and When it's done I want to switch the active profile from 'install' to 'normal' and refresh the application context, so the Spring can init every bean that needs DB data source.

I can modify the list of active profiles from code, without problems, but when i try to refresh the application context, i get the following exception:

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

This is how i boot my Spring boot app:

`new SpringApplicationBuilder().sources(MyApp.class)
.profiles("my-profile").build().run(args);` 

Does anybody know how to initiate spring boot app that let's you refresh the app context multiple times ?


回答1:


You can't just refresh an existing context. You have to close the old one and create a new one. You can see how we do it in Spring Cloud here: https://github.com/spring-cloud/spring-cloud-commons/blob/master/spring-cloud-context/src/main/java/org/springframework/cloud/context/restart/RestartEndpoint.java. If you want to you can include that Endpoint just by adding spring-cloud-context as a dependency, or you can copy the code I guess and use it in your own "endpoint".

Here's the endpoint implementation (some details missing in fields):

@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;
}


来源:https://stackoverflow.com/questions/28541138/modify-active-profiles-and-refresh-applicationcontext-runtime-in-a-spring-boot-a

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!