Home > Mobile >  Multiple DataSources across 2 components
Multiple DataSources across 2 components

Time:09-21

I have 2 Spring Boot applications App1 and App2. App2 can run as a standalone application and also is embedded in application App1 as a dependency. I want App1 to be able to make calls to services of App2 which makes repo calls to a different DB. I have configured DataSource beans in both components as follows:

App1

  @Configuration
  @EnableJpaRepositories(basePackages = "com.ev.app1.repositories",
  entityManagerFactoryRef = "app1EntityManagerFactory",
  transactionManagerRef = "app1TransactionManager")
  public class PersistenceApp1Configuration {
    @Bean
    @ConfigurationProperties(prefix = "app.datasource.app1")
    public DataSourceProperties app1DataSourceProperties() {
      return new DataSourceProperties();
    }

    @Bean(name = "app1DataSource")
    @ConfigurationProperties(prefix = "app.datasource.app1")
    public DataSource tmDataSource() {
      return tmDataSourceProperties().initializeDataSourceBuilder()
      .type(BasicDataSource.class).build();
    }

App1 application.properties:

app.datasource.app1.url=jdbc:postgresql://localhost:5432/mercury_tmdb?currentSchema=txm
app.datasource.app1.username=postgres
app.datasource.app1.password=root
app.datasource.app1.driverClassName=org.postgresql.Driver

App2

  @Configuration
  @EnableJpaRepositories(basePackages = "com.ev.app1.repositories",
  entityManagerFactoryRef = "app1EntityManagerFactory",
  transactionManagerRef = "app1TransactionManager")
  public class PersistenceApp1Configuration {
    @Bean
    @ConfigurationProperties(prefix = "app.datasource.app1")
    public DataSourceProperties app1DataSourceProperties() {
      return new DataSourceProperties();
    }

    @Bean(name = "app2DataSource")
    @Primary
    @ConfigurationProperties(prefix = "app.datasource.app2")
    public DataSource app2DataSource() {
    return tmDataSourceProperties().initializeDataSourceBuilder()
      .type(BasicDataSource.class).build();
    }

App2 application.properties:

app.datasource.app2.url=jdbc:postgresql://localhost:5432/mercury_cldb?currentSchema=led
app.datasource.app2.username=postgres
app.datasource.app2.password=root
app.datasource.app2.driverClassName=org.postgresql.Driver

As you can see, I had to mark the DataSource bean in App2 as @Primary to override the default spring datasource. But the same I cannot do for App1 since it already has a Primary bean from App2. Any work around for this? Or may be I am completely off with this approach?

Note: I have other config beans which I haven't shown here but I can share if required

CodePudding user response:

You can use the conditional bean configuration from Spring, so you can decide when to use each datasource.

You can use the annotation like this:

@ConditionalOnExpression(value = "${module.enabled} and ${module.submodule.enabled}")

depending on your specific configuration.

  • Related