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:
- Define multiple
DataSourcebeans with different connection settings. - Use
@Primaryannotations to specify the main data source. - If necessary, create separate
EntityManagerFactoryandTransactionManagerfor 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.