Home >Java >javaTutorial >How to Configure and Use Multiple Data Sources in a Spring Boot Application?
Problem:
How can multiple data sources be configured and utilized in a Spring Boot application?
Solution:
Modify the application.properties file to include the settings for an additional data source. For example:
#first db spring.datasource.url = [url] spring.datasource.username = [username] spring.datasource.password = [password] spring.datasource.driverClassName = oracle.jdbc.OracleDriver #second db spring.secondDatasource.url = [url] spring.secondDatasource.username = [username] spring.secondDatasource.password = [password] spring.secondDatasource.driverClassName = oracle.jdbc.OracleDriver
In a class annotated with @Configuration, create methods with the @Bean annotation to define the data source instances. Specify the @Primary annotation to indicate the primary data source. For example:
@Bean @Primary @ConfigurationProperties(prefix = "spring.datasource") public DataSource primaryDataSource() { return DataSourceBuilder.create().build(); } @Bean @ConfigurationProperties(prefix = "spring.secondDatasource") public DataSource secondaryDataSource() { return DataSourceBuilder.create().build(); }
Autowire the desired data source in the repository class using the @Qualifier annotation. For example:
@Repository public class ExampleRepository { @Autowired @Qualifier("secondaryDataSource") private DataSource dataSource; // Operations using the secondary data source }
By following these steps, you can configure and use multiple data sources in a Spring Boot application, enabling you to connect to and manage different data sources within your system.
The above is the detailed content of How to Configure and Use Multiple Data Sources in a Spring Boot Application?. For more information, please follow other related articles on the PHP Chinese website!