Sobes.tech
Junior — Middle

How to configure the selection of the primary database in an application with multiple data sources in Spring Boot?

sobes.tech AI

Answer from AI

In Spring Boot, to work with multiple data sources and select the primary database, the usual approach is:

  1. Define multiple DataSource beans with different connection settings.
  2. Use @Primary annotations to specify the main data source.
  3. If necessary, create separate EntityManagerFactory and TransactionManager for each source.

Example configuration with two data sources, where one is marked as primary:

@Configuration
public class DataSourceConfig {

    @Bean
    @Primary
    @ConfigurationProperties(prefix = "spring.datasource.primary")
    public DataSource primaryDataSource() {
        return DataSourceBuilder.create().build();
    }

    @Bean
    @ConfigurationProperties(prefix = "spring.datasource.secondary")
    public DataSource secondaryDataSource() {
        return DataSourceBuilder.create().build();
    }

    // You can add EntityManagerFactory and TransactionManager for each DataSource
}

In application.properties or application.yml, connection parameters for each source are specified with different prefixes.

Thus, Spring Boot will use primaryDataSource as the main, and others as additional.