0 votes
1 view
in Java by (10.2k points)

I am new to Spring and Spring Boot. How can I configure and use two data sources?

For example here is what I have for the first data source:

application.properties

#first db

spring.datasource.url = [url]

spring.datasource.username = [username]

spring.datasource.password = [password]

spring.datasource.driverClassName = oracle.jdbc.OracleDriver

#second db ...

Application class

@SpringBootApplication

public class SampleApplication

{

    public static void main(String[] args) {

        SpringApplication.run(SampleApplication.class, args);

    }

}

How do I modify application.properties to add another data source? How do I autowire it to be used by a different repository?

1 Answer

0 votes
by (46.1k points)

Here you go

#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

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

}

Welcome to Intellipaat Community. Get your technical queries answered by top developers !


Categories

...