Home >Java >javaTutorial >How to Configure and Use Multiple Data Sources in Spring Boot?

How to Configure and Use Multiple Data Sources in Spring Boot?

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2024-12-18 18:36:14699browse

How to Configure and Use Multiple Data Sources in Spring Boot?

Configuring and Using Multiple Data Sources in Spring Boot

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:

Application Properties and Data Sources

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

Bean Configuration

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();
}

Autowiring and Usage

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn