Modify Active Profiles and Update ApplicationContext Runtime in Spring Boot Application

I have a Spring boot web application. The application is configured using java classes using the @Configurable annotation. I entered two profiles: "install", "normal". If the installation profile is active, none of the Beans that require a DB connection are loaded. I want to create a controller in which the user can configure db connection parameters. When this is done, I want to switch the active profile from "install" to "normal" and update the application context, so Spring can initialize every bean that needs a database data source.

I can change the list of active profiles from code without problems, but when I try to update 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 download the Spring boot application:

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

Does anyone know how to run Spring's download application that allows you to update the application context several times?

+7
java spring-boot spring-profiles refresh applicationcontext
source share
1 answer

You cannot just update an existing context. You must 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, you can enable this Endpoint by simply adding spring -cloud-context as a dependency, or you can copy the code I assume and use it in your own "endpoint".

Here's the endpoint implementation (some details are missing in the 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; } 
+13
source share

All Articles