In Spring Boot applications, it's possible to configure and utilize multiple data sources. This flexibility allows developers to manage data from different databases or perform specific operations based on the data source. Here's an example to demonstrate the configuration and usage:
Add the following properties to your application.properties file:
# First Data Source spring.datasource.url=[URL] spring.datasource.username=[USERNAME] spring.datasource.password=[PASSWORD] spring.datasource.driverClassName=oracle.jdbc.OracleDriver # Second Data Source spring.secondDatasource.url=[URL] spring.secondDatasource.username=[USERNAME] spring.secondDatasource.password=[PASSWORD] spring.secondDatasource.driverClassName=oracle.jdbc.OracleDriver
In a class annotated with @Configuration, define methods to create and configure each data source as beans:
@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(); }
To autowire the primary data source for a repository:
@Repository public class UserRepository { @Autowired private EntityManager entityManager; // ... }
To autowire the secondary data source for a different repository:
@Repository public class OrderRepository { @Autowired @Qualifier("secondaryDataSource") private EntityManager entityManager; // ... }
By adding @Qualifier("secondaryDataSource") to the entityManager field, Spring will inject the secondary data source instead of the primary one.
The above is the detailed content of How to Configure and Use Multiple Data Sources in Spring Boot?. For more information, please follow other related articles on the PHP Chinese website!