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

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

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2024-12-23 14:48:11885browse

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

Spring Boot Configuration and Utilization of Two Data Sources

Problem:

How can multiple data sources be configured and utilized in a Spring Boot application?

Solution:

Application Configuration

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

Spring Bean Configuration

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

Repository Autowiring

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!

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