{"id":4034,"date":"2026-11-26T17:52:31","date_gmt":"2026-11-26T09:52:31","guid":{"rendered":"http:\/\/www.efedavetiye.com\/blog\/?p=4034"},"modified":"2026-11-26T17:52:31","modified_gmt":"2026-11-26T09:52:31","slug":"how-to-configure-multiple-datasources-in-spring-boot-4c47-fca6ed","status":"publish","type":"post","link":"http:\/\/www.efedavetiye.com\/blog\/2026\/11\/26\/how-to-configure-multiple-datasources-in-spring-boot-4c47-fca6ed\/","title":{"rendered":"How to configure multiple datasources in Spring Boot?"},"content":{"rendered":"<p>If you\u2019ve spent any time with Spring Boot, you\u2019ve likely built apps that talk to one database\u2014maybe 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: \u201cHow do I configure multiple datasources in Spring Boot without breaking the app, running into transaction issues, or fighting with auto-configuration?\u201d <a href=\"https:\/\/www.flipflowscreen.com\/spring\/\">Spring<\/a><\/p>\n<p><img decoding=\"async\" src=\"https:\/\/www.flipflowscreen.com\/uploads\/45042\/small\/elastic-screen-plateac177.jpg\"><\/p>\n<p>A lot of developers stumble here because Spring Boot\u2019s 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 <code>application.properties<\/code> and call it a day, you\u2019ll get a <code>NoUniqueBeanDefinitionException<\/code> telling Spring it can\u2019t decide which <code>DataSource<\/code> bean to use. That\u2019s the problem we solve for our clients all the time\u2014by walking through explicit, testable configurations that play nice with Spring\u2019s context, JPA repositories, and transaction management.<\/p>\n<p>Let\u2019s start with the basics. First, you\u2019ll need two key annotations to tell Spring not to auto-configure its default datasource. The <code>@SpringBootApplication<\/code> annotation will still work, but we add <code>@EnableAutoConfiguration(exclude = {DataSourceAutoConfiguration.class, DataSourceTransactionManagerAutoConfiguration.class})<\/code> to turn off those default auto-configs. That removes ambiguity and lets us define our own beans, which is critical for multiple datasource setups.<\/p>\n<p>Next, define your datasource properties in <code>application.properties<\/code> or <code>application.yml<\/code>. I recommend keeping them grouped by datasource to keep things clear. For example, if you have a <code>primary<\/code> datasource for core transactional data and a <code>secondary<\/code> datasource for read-heavy reporting, your properties would look like this:<\/p>\n<pre><code class=\"language-properties\">primary.datasource.url=jdbc:postgresql:\/\/localhost:5432\/core_db\nprimary.datasource.username=admin\nprimary.datasource.password=core_pass\nprimary.datasource.driver-class-name=org.postgresql.Driver\n\nsecondary.datasource.url=jdbc:mysql:\/\/localhost:3308\/reporting_db\nsecondary.datasource.username=report_user\nsecondary.datasource.password=report_pass\nsecondary.datasource.driver-class-name=com.mysql.cj.jdbc.Driver\n<\/code><\/pre>\n<p>This naming pattern isn\u2019t arbitrary\u2014it\u2019s how we\u2019ll tell Spring apart between the two. Now, create a configuration class for the primary datasource first. We\u2019ll use <code>@Configuration<\/code> and <code>@Primary<\/code> to mark this as the default bean, since some auto-configured dependencies still expect a single primary datasource in many Spring starters. We\u2019ll also create a <code>LocalContainerEntityManagerFactoryBean<\/code> for JPA, and a <code>PlatformTransactionManager<\/code> tied specifically to this primary datasource.<\/p>\n<p>Wait\u2014one 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 <code>@EntityScan<\/code> and <code>@EnableJpaRepositories<\/code> annotations that target only the packages for the primary datasource. For example, if all core entities live in <code>com.yourcompany.core.model<\/code> and core repositories in <code>com.yourcompany.core.repository<\/code>, those annotations would look like:<\/p>\n<pre><code class=\"language-java\">@Configuration\n@EnableTransactionManagement\n@EntityScan(basePackages = &quot;com.yourcompany.core.model&quot;)\n@EnableJpaRepositories(\n    basePackages = &quot;com.yourcompany.core.repository&quot;,\n    entityManagerFactoryRef = &quot;primaryEntityManagerFactory&quot;,\n    transactionManagerRef = &quot;primaryTransactionManager&quot;\n)\npublic class PrimaryDatasourceConfig {\n    \/\/ Primary datasource bean, entity manager, and transaction manager go here\n}\n<\/code><\/pre>\n<p>Inside this config, we define the <code>DataSource<\/code> bean using the properties we set earlier, pulling them from the environment with <code>@Value<\/code> or <code>@ConfigurationProperties<\/code> (I prefer <code>@ConfigurationProperties<\/code> 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 <code>@Transactional<\/code> without a qualifier uses this primary datasource.<\/p>\n<p>Now repeat the exact same pattern for the secondary datasource\u2014just without the <code>@Primary<\/code> annotation, and with different ref names. The secondary config will have its own <code>@EntityScan<\/code> for reporting entities, and <code>@EnableJpaRepositories<\/code> 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\u2019s no overlap.<\/p>\n<p>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\u2019ll 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 <code>@Transactional(&quot;secondaryTransactionManager&quot;)<\/code> 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\u2014especially if you need cross-datasource transactions, which are much more complex and often not worth the overhead unless absolutely necessary.<\/p>\n<p>Let\u2019s 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\u2014HikariCP is the default for Spring Boot, so you can add <code>hikari<\/code> properties per datasource, like <code>primary.datasource.hikari.maximum-pool-size=10<\/code> and <code>secondary.datasource.hikari.maximum-pool-size=15<\/code> to match their workloads. We also use JPA properties like <code>hibernate.ddl-auto<\/code> selectively\u2014for primary datasources, that\u2019s usually <code>none<\/code> or <code>validate<\/code> in production, while secondary might use <code>update<\/code> or even <code>create-only<\/code> if it\u2019s a read replica.<\/p>\n<p>Another common use case we see is when one datasource is not a SQL database\u2014like 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\u2019s 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.<\/p>\n<p>Testing is also easier when you follow this pattern. You can use Spring Boot\u2019s <code>@TestPropertySource<\/code> 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\u2014this avoids embarrassing production issues where data ends up in the wrong database.<\/p>\n<p>Wait a minute\u2014what 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 <code>@EnableJpaRepositories<\/code> and <code>@EntityScan<\/code> annotations\u2014those 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.<\/p>\n<p>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\u2014whether for compliance, legacy system integration, or performance optimization\u2014the configuration we\u2019ve walked through is battle-tested, well-documented, and works with modern Spring Boot versions (2.7 and 3.x, the current LTS releases). We\u2019ve used this setup for everything from small business apps to enterprise-scale SaaS platforms, and it\u2019s never failed when implemented correctly.<\/p>\n<p><img decoding=\"async\" src=\"https:\/\/www.flipflowscreen.com\/uploads\/45042\/small\/pellet-screen-plate0b7a4.jpg\"><\/p>\n<p>If you\u2019re dealing with a multiple-datasource setup that\u2019s giving you trouble\u2014whether it\u2019s bean conflicts, transaction errors, or performance issues\u2014our 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\u2019re ready to stop fighting with datasource configurations and start building features, reach out to us to discuss your requirements.<\/p>\n<p><a href=\"https:\/\/www.flipflowscreen.com\/spare-parts\/\">Spare Parts<\/a> References<br \/>\nSpring Boot Documentation, Multiple Data Sources<br \/>\nJPA, EntityManager and Persistence Unit in Java<br \/>\nHikariCP Connection Pool Configuration<br \/>\nSpring Framework Transaction Management<\/p>\n<hr>\n<p><a href=\"https:\/\/www.flipflowscreen.com\/\">Xinxiang Fengda Machinery Co., Ltd.<\/a><br \/>We&#8217;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.<br \/>Address: No.16 Wangguanying Village, Kangcun Town, Huojia County, Xinxiang City, Henan Province, China<br \/>E-mail: xxfdjx@163.com<br \/>WebSite: <a href=\"https:\/\/www.flipflowscreen.com\/\">https:\/\/www.flipflowscreen.com\/<\/a><\/p>\n","protected":false},"excerpt":{"rendered":"<p>If you\u2019ve spent any time with Spring Boot, you\u2019ve likely built apps that talk to one &hellip; <a title=\"How to configure multiple datasources in Spring Boot?\" class=\"hm-read-more\" href=\"http:\/\/www.efedavetiye.com\/blog\/2026\/11\/26\/how-to-configure-multiple-datasources-in-spring-boot-4c47-fca6ed\/\"><span class=\"screen-reader-text\">How to configure multiple datasources in Spring Boot?<\/span>Read more<\/a><\/p>\n","protected":false},"author":859,"featured_media":4034,"comment_status":"closed","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[1],"tags":[3997],"class_list":["post-4034","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-industry","tag-spring-4fbe-fce089"],"_links":{"self":[{"href":"http:\/\/www.efedavetiye.com\/blog\/wp-json\/wp\/v2\/posts\/4034","targetHints":{"allow":["GET"]}}],"collection":[{"href":"http:\/\/www.efedavetiye.com\/blog\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"http:\/\/www.efedavetiye.com\/blog\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"http:\/\/www.efedavetiye.com\/blog\/wp-json\/wp\/v2\/users\/859"}],"replies":[{"embeddable":true,"href":"http:\/\/www.efedavetiye.com\/blog\/wp-json\/wp\/v2\/comments?post=4034"}],"version-history":[{"count":0,"href":"http:\/\/www.efedavetiye.com\/blog\/wp-json\/wp\/v2\/posts\/4034\/revisions"}],"wp:featuredmedia":[{"embeddable":true,"href":"http:\/\/www.efedavetiye.com\/blog\/wp-json\/wp\/v2\/posts\/4034"}],"wp:attachment":[{"href":"http:\/\/www.efedavetiye.com\/blog\/wp-json\/wp\/v2\/media?parent=4034"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"http:\/\/www.efedavetiye.com\/blog\/wp-json\/wp\/v2\/categories?post=4034"},{"taxonomy":"post_tag","embeddable":true,"href":"http:\/\/www.efedavetiye.com\/blog\/wp-json\/wp\/v2\/tags?post=4034"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}