Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

On-the-fly DB reconfiguration in Spring Boot application

I have quite a complex Spring Boot application (including Spring MVC and Security), which among other things requires a database configuration (url, username and password). The requirement is to let end-user configure the DB with the help of the application itself, like the following:

  1. User starts the application, which has no DB configuration yet
  2. Application notices the absence of DB configuration and presents user with configuration screen
  3. User enters url and credentials
  4. Application starts using this DB

The obvious problem is that I cannot create any beans that require a DataSource which requires DB configuration until that configuration is known.

Is there any way to postpone the initialisation of the majority of the application's beans until first configuration step is performed?

-- Update -- Several of application's beans initialise their state from the DB in their @PostConsutrct methods. So I either need to really delay their creation or have a method of refreshing (potentially) all beans in the application context after configuration is provided.

like image 617
Nikem Avatar asked May 26 '16 17:05

Nikem


People also ask

What is @configuration in spring boot?

Spring @Configuration annotation is part of the spring core framework. Spring Configuration annotation indicates that the class has @Bean definition methods. So Spring container can process the class and generate Spring Beans to be used in the application.

How do I configure multiple datasources in spring boot application?

So, to use multiple data sources, we need to declare multiple beans with different mappings within Spring's application context. The configuration for the data sources must look like this: spring: datasource: todos: url: ... username: ...

What is the use of @SpringBootApplication?

Spring Boot @SpringBootApplication annotation is used to mark a configuration class that declares one or more @Bean methods and also triggers auto-configuration and component scanning. It's same as declaring a class with @Configuration, @EnableAutoConfiguration and @ComponentScan annotations.


1 Answers

I suggest you could think about having another module/program or a simple script that would ask to provide all details like database etc, store this information to your application.properties file (may be useful re externalized configuration Spring boot external configuration) and then launch your main program with already available information on datasource. This might be a bit easier approach.

like image 82
lenach87 Avatar answered Oct 07 '22 01:10

lenach87