10

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 Answer 1

14

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;
}
3
  • Unfortunately the link has died. Any chance you could include the basic code here?
    – DB5
    Apr 16, 2015 at 14:46
  • 1
    @DaveSyer Sir, Can this be done without Springboot also? Feb 16, 2018 at 5:05
  • I don’t see why not. But you’d need a way to bootstrap the context (and remember its sources). That’s what the “application” is doing in that code snippet.
    – Dave Syer
    Feb 16, 2018 at 7:46

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.