Home >Java >javaTutorial >How to Integrate Multiple Data Sources in a Spring Boot Application?

How to Integrate Multiple Data Sources in a Spring Boot Application?

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2024-12-20 13:39:10921browse

How to Integrate Multiple Data Sources in a Spring Boot Application?

Multiple Data Sources in Spring Boot

Integrating multiple data sources into a Spring Boot application can enhance flexibility and data isolation. To configure and use two data sources:

1. Configure Data Sources in application.properties:

Add the following configurations to your application.properties file:

#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

2. Create Bean Methods in @Configuration Class:

In a class annotated with @Configuration, add the following methods to instantiate data sources:

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

3. Autowire Data Sources:

In your repositories or services, autowire the desired data source using @Autowired and @Qualifier. The @Qualifier annotation specifies which data source to inject.

@Autowired
@Qualifier("primaryDataSource")
private DataSource primaryDataSource;

@Autowired
@Qualifier("secondaryDataSource")
private DataSource secondaryDataSource;

By following these steps, you can configure and use multiple data sources in your Spring Boot application, allowing you to work with different databases seamlessly.

The above is the detailed content of How to Integrate Multiple Data Sources in a Spring Boot Application?. 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