How do you configure and connect multiple databases in a Spring Boot application?

Connecting multiple databases in a Spring Boot application requires explicitly defining separate DataSource, EntityManagerFactory, and TransactionManager beans for each database, since Spring Boot's auto-configuration only handles a single default data source.

Key Points

Example

An application reading from a legacy reporting database and writing to a primary transactional database defines two full sets of DataSource/EntityManagerFactory/TransactionManager beans, with @Primary on the transactional database's beans and @Qualifier used wherever the reporting database is accessed.

@Bean
@Primary
@ConfigurationProperties("app.datasource.primary")
public DataSource primaryDataSource() {
    return DataSourceBuilder.create().build();
}

@Bean
@ConfigurationProperties("app.datasource.reporting")
public DataSource reportingDataSource() {
    return DataSourceBuilder.create().build();
}

Interview Tip

A concise interview answer is

I define a separate DataSource, EntityManagerFactory, and TransactionManager for each database in its own configuration class, mark one set as @Primary, and use @Qualifier wherever I need to inject the other explicitly. Repositories are split into separate packages so each one is wired to the correct EntityManagerFactory.

Last updated: 16 July 2026

Previous question: Can you use both application.yml and application.properties in a Spring Boot project? If so, how are they prioritized?

Next question: What is the difference between returning a ResponseEntity vs directly returning an object in a REST API?

More Spring Boot - Level IV (Advanced) interview questions

All Spring Boot - Level IV (Advanced) questions