by BehindJava

How to configure Two DataSources in Spring Boot Application

Home » springboot » How to configure Two DataSources in Spring Boot Application

In this tutorial we are going to learn about configuring two data sources in a Spring Boot application.

when we generate a Spring Boot project using Spring Initializr or Spring tool suite IDE a file named application.properties is also generated by default with the project under src/main/resources directory.

Add in 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

Add in any class annotated with @Configuration the following methods:

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