If you’ve spent any time with Spring Boot, you’ve likely built apps that talk to one database—maybe a PostgreSQL backend for your customer data, or an in-memory H2 database for prototyping. But at some point, your use case will outgrow a single datasource. Maybe you need to fetch inventory data from a legacy MySQL system while writing new user data to a modern MongoDB instance, or split transactional data and analytics across two separate databases to improve performance. As a Spring Solutions provider, my team and I get this question every week: “How do I configure multiple datasources in Spring Boot without breaking the app, running into transaction issues, or fighting with auto-configuration?” Spring

A lot of developers stumble here because Spring Boot’s default auto-configuration works great for single datasource setups, but when you add a second one, those default beans start overlapping. If you just drop two database connection strings into your application.properties and call it a day, you’ll get a NoUniqueBeanDefinitionException telling Spring it can’t decide which DataSource bean to use. That’s the problem we solve for our clients all the time—by walking through explicit, testable configurations that play nice with Spring’s context, JPA repositories, and transaction management.
Let’s start with the basics. First, you’ll need two key annotations to tell Spring not to auto-configure its default datasource. The @SpringBootApplication annotation will still work, but we add @EnableAutoConfiguration(exclude = {DataSourceAutoConfiguration.class, DataSourceTransactionManagerAutoConfiguration.class}) to turn off those default auto-configs. That removes ambiguity and lets us define our own beans, which is critical for multiple datasource setups.
Next, define your datasource properties in application.properties or application.yml. I recommend keeping them grouped by datasource to keep things clear. For example, if you have a primary datasource for core transactional data and a secondary datasource for read-heavy reporting, your properties would look like this:
primary.datasource.url=jdbc:postgresql://localhost:5432/core_db
primary.datasource.username=admin
primary.datasource.password=core_pass
primary.datasource.driver-class-name=org.postgresql.Driver
secondary.datasource.url=jdbc:mysql://localhost:3308/reporting_db
secondary.datasource.username=report_user
secondary.datasource.password=report_pass
secondary.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
This naming pattern isn’t arbitrary—it’s how we’ll tell Spring apart between the two. Now, create a configuration class for the primary datasource first. We’ll use @Configuration and @Primary to mark this as the default bean, since some auto-configured dependencies still expect a single primary datasource in many Spring starters. We’ll also create a LocalContainerEntityManagerFactoryBean for JPA, and a PlatformTransactionManager tied specifically to this primary datasource.
Wait—one common mistake here is reusing the same package scan path for JPA repositories, which would cause Spring to try to map entities from both datasources to both persistence units. So we need to add @EntityScan and @EnableJpaRepositories annotations that target only the packages for the primary datasource. For example, if all core entities live in com.yourcompany.core.model and core repositories in com.yourcompany.core.repository, those annotations would look like:
@Configuration
@EnableTransactionManagement
@EntityScan(basePackages = "com.yourcompany.core.model")
@EnableJpaRepositories(
basePackages = "com.yourcompany.core.repository",
entityManagerFactoryRef = "primaryEntityManagerFactory",
transactionManagerRef = "primaryTransactionManager"
)
public class PrimaryDatasourceConfig {
// Primary datasource bean, entity manager, and transaction manager go here
}
Inside this config, we define the DataSource bean using the properties we set earlier, pulling them from the environment with @Value or @ConfigurationProperties (I prefer @ConfigurationProperties for cleaner code, especially as the number of properties grows). Then we build the entity manager factory, set its packages to scan, and tie it to the primary datasource. Finally, the transaction manager is tied to the primary entity manager factory, so any transaction annotated with @Transactional without a qualifier uses this primary datasource.
Now repeat the exact same pattern for the secondary datasource—just without the @Primary annotation, and with different ref names. The secondary config will have its own @EntityScan for reporting entities, and @EnableJpaRepositories targeting the reporting repository package, pointing to the secondary entity manager factory and secondary transaction manager. This way, Spring knows exactly which repositories belong to which datasource, and there’s no overlap.
Transaction handling is the big gotcha here. If you forget to specify which transaction manager to use for secondary-datasource operations, Spring will default to the primary one, and you’ll get errors when trying to commit or rollback against the wrong database. To fix this, when you call a secondary repository method, you just add @Transactional("secondaryTransactionManager") to that method or service class. This is also where a lot of teams run into issues with nested transactions or propagation, so I always recommend testing transaction behavior explicitly for each datasource—especially if you need cross-datasource transactions, which are much more complex and often not worth the overhead unless absolutely necessary.
Let’s also talk about real-world adjustments we make for production, because the setup above works great for local testing but needs tweaks for reliability. For example, adding connection pool settings to both datasources—HikariCP is the default for Spring Boot, so you can add hikari properties per datasource, like primary.datasource.hikari.maximum-pool-size=10 and secondary.datasource.hikari.maximum-pool-size=15 to match their workloads. We also use JPA properties like hibernate.ddl-auto selectively—for primary datasources, that’s usually none or validate in production, while secondary might use update or even create-only if it’s a read replica.
Another common use case we see is when one datasource is not a SQL database—like MongoDB, Redis, or a legacy NoSQL system. The same core pattern applies: configure the separate beans, tell Spring which repositories and entities (or in MongoDB’s case, collections) map to which, and ensure transaction management is scoped correctly. We recently worked with a SaaS client that needed to store user profile data in PostgreSQL and activity logs in MongoDB, and this exact multiple-datasource setup let them build it without refactoring their entire persistence layer.
Testing is also easier when you follow this pattern. You can use Spring Boot’s @TestPropertySource to override specific datasource properties for integration tests, or use embedded databases for testing each datasource independently. We write test cases that verify that when we call a core repository, it hits the primary datasource, and when we call a reporting repository, it hits the secondary—this avoids embarrassing production issues where data ends up in the wrong database.
Wait a minute—what if you have more than two datasources? Say three or four for different regional deployments? The same approach scales. Just create additional config classes, each with their own properties, entity scans, and repository packages. The key is never skipping the explicit naming of beans and the @EnableJpaRepositories and @EntityScan annotations—those are what prevent Spring from auto-wiring the wrong components. A lot of developers think Spring Boot is magic, but when it comes to multiple datasources, you have to explicitly tell it where to look, otherwise it will guess wrong.
As a Spring Solutions provider, one thing we always emphasize is avoiding overcomplicating things. If you can split workloads with read replicas first, do that before adding a second datasource. But when multiple datasources are unavoidable—whether for compliance, legacy system integration, or performance optimization—the configuration we’ve walked through is battle-tested, well-documented, and works with modern Spring Boot versions (2.7 and 3.x, the current LTS releases). We’ve used this setup for everything from small business apps to enterprise-scale SaaS platforms, and it’s never failed when implemented correctly.

If you’re dealing with a multiple-datasource setup that’s giving you trouble—whether it’s bean conflicts, transaction errors, or performance issues—our team can help you audit your current configuration, optimize it for your specific use case, and build a scalable, maintainable persistence layer that fits your Spring Boot stack. We work with teams of all sizes, from startups just launching their first multi-datasource app to enterprise teams updating legacy systems, so we know how to tailor solutions to your exact needs. If you’re ready to stop fighting with datasource configurations and start building features, reach out to us to discuss your requirements.
Spare Parts References
Spring Boot Documentation, Multiple Data Sources
JPA, EntityManager and Persistence Unit in Java
HikariCP Connection Pool Configuration
Spring Framework Transaction Management
Xinxiang Fengda Machinery Co., Ltd.
We’re well-known as one of the leading spring manufacturers and suppliers in China, specialized in providing high quality customized service for global clients. We warmly welcome you to buy high-grade spring made in China here from our factory.
Address: No.16 Wangguanying Village, Kangcun Town, Huojia County, Xinxiang City, Henan Province, China
E-mail: xxfdjx@163.com
WebSite: https://www.flipflowscreen.com/