1

Spring Boot : How to add new Datasource at runtime

My project want to connect two datasource.

The first datasource I can Config in application.properties but the second datasource can't config because this config is in the tableConfig from DB of the first datasource.

So,

  1. config the 1st datasource.
  2. query data from the 1st datasource for get config of 2nd datasource (url, username, password).
  3. add new 2nd datasource

Now, I config two Datasource from application.properties and it's work.

But the requirement want to change the 2nd datasource from table of 1st datasource. T.T

Please, gives me some suggestions.

Thank you.

methodplayer
  • 43
  • 1
  • 8

1 Answers1

0

A Spring configuration like this should work (consider it pseudo code):

@Bean("secondDatasource")
public Datasource secondDatasource(@Qualifier("firstDatasource") Datasource ds){
    // use `ds` to obtain the necessary information to obtain a datasource ...
    return DataSourceBuilder
        .create()
        .username(username)
        .password(pwd)
        .url(url)
        .driverClassName(driver)
        .build();
}

I would at least start without using Spring Data JPA in the configuration class and operate directly on the data source to keep things simple.

You already got pointers, how to set up Spring Data JPA to then use the different data sources: http://www.baeldung.com/spring-data-jpa-multiple-databases

The code above is mainly just copied from: https://stackoverflow.com/a/28822145

Jens Schauder
  • 65,795
  • 24
  • 148
  • 294