Define Multiple DataSources in Spring Boot


This tutorial will show you how you can define multiple datasources in Spring Boot application. I had shown how to define multiple datasources in Spring application, but here I will define multiple datasources in Spring Boot application. There may be situations where you need to define multiple datasources in Spring Boot application.

For instance, you may need to define multiple datasources for your Liquibase applications.  You can have different datasource bean ids configured into the Spring configuration class and you can use those datasources as per our needs in the different classes when required by accessing the bean id reference.

Related Posts:


Java at least 1.8, Maven or Gradle, Spring Boot dependencies

Define Multiple DataSources

Assuming your Spring Boot application is already configured using the above dependencies and you want to define multiple datasources in your application.

Datasource Details

As a first step define your two or more datasources into file under classpath directory src/main/resources.

#datasource one
spring.datasource.url=jdbc:Oracle:thin:@//<host>:<port>/<service name>

#datasource two
spring.secondaryDatasource.url=jdbc:Oracle:thin:@//<host>:<port>/<service name>

In the above file you see I have added two datasources of Oracle type. If you want you can also add different database type datasources and more than even two datasources.

Now you need to define bean for different datasources declared into So I will create a Spring configuration class  DatabaseConfig annotated with @Configuration.

Configuration Class

In the below Spring configuration class I have defined two beans for two different datasources. You can also assigned name to each bean so that it would be easier for you to work with the different datasources at Repository or DAO layer.

I am referring the different datasource properties using Spring @ConfigurationProperties annotation.

public class DatabaseConfig {

    @ConfigurationProperties(prefix = "spring.datasource")
    public DataSource primaryDataSource() {
        return DataSourceBuilder.create().build();

    @ConfigurationProperties(prefix = "spring.secondaryDatasource")
    public DataSource secondaryDataSource() {
        return DataSourceBuilder.create().build();


That’s all. Hope you got idea how to define multiple datasources in Spring Boot application.

Leave a Reply

Your email address will not be published. Required fields are marked *