How to Configure Multiple Data Sources in a Spring Boot Application

Tech Lead & Architect | 13+ Years in Cloud, Backend, and AI - Experienced software engineer with expertise in Java, Spring Boot, Microservices, Angular, React, Kafka, DevOps, Python, PySpark, Databricks, and Generative AI. Certified in TOGAF, AWS, and Google Cloud. Passionate about building scalable, secure, and high-performance systems. Enthusiast in Data Engineering & Agentic AI. Author of 1,200+ technical articles sharing insights across diverse tech stacks.
Date: 2020-11-23
Configuring Multiple Data Sources in a Spring Boot Application
This article explains how to set up a Spring Boot application to connect to and manage multiple databases simultaneously. We'll explore the concepts involved, focusing on the architecture and configuration required to achieve this functionality. The example uses two separate H2 databases, but the principles can be applied to other database systems. A basic understanding of Spring Boot is assumed.
Understanding the Need for Multiple Data Sources
Often, applications need to interact with more than one database. This might be because of legacy systems, different data types, or the need to separate concerns for better organization and maintainability. Instead of combining all data into a single, potentially unwieldy database, it's often more efficient and organized to maintain separate databases, each with its specific purpose. This approach helps to improve data integrity, performance, and the overall manageability of the application. This tutorial demonstrates how to achieve this multi-database connectivity within the structure of a Spring Boot application.
Setting Up the Project
We begin by establishing the project environment. The specific development tools used in the original example are Eclipse Kepler SR2, JDK 8, and Maven. These are common tools used for Java development and build management. While the specifics of the IDE and JDK version may vary, the core principles outlined below remain consistent across different environments. Maven is crucial for managing project dependencies, essentially streamlining the process of including necessary libraries and components.
Defining Dependencies
The project requires several dependencies, which are typically specified in a pom.xml file (Project Object Model). These dependencies include Spring Boot modules (for web functionality, JPA for database interactions, and a configuration processor), the H2 database (an in-memory database ideal for testing and development), Lombok (a utility to simplify Java code), and a Java Faker library (for generating sample data). Maven automatically handles the resolution of transitive dependencies; meaning that if a dependency relies on other libraries, Maven will automatically download and include those as well.
Configuring Data Sources
A crucial aspect of this setup is defining the data sources themselves. This is typically done in an application.properties file. This file holds configuration settings for the application, including database connection details. In our scenario, we will define two distinct data sources, each pointing to a separate H2 database. These configurations will specify connection URLs, usernames, and passwords for each database. These are the critical parameters that Spring Boot will use to establish and manage the connections to the respective databases.
Creating the Database Models
The next step involves defining the data structures for each database. This involves creating Java classes that represent the tables in the databases (often referred to as entity classes). For example, we might have a Beer class representing a table in the "beerdb" database and a Customer class for the "customerdb" database. These classes use annotations (metadata that provides instructions to the framework) to map the Java objects to the database tables, specifying data types and relationships between the data. The process of mapping the Java objects to the database tables is a core functionality provided by the JPA (Java Persistence API) framework.
Configuring Spring Beans
Spring Boot uses the concept of "beans," which are essentially objects that form the core components of the application. We create separate configuration classes, such as BeerConfig and CustomerConfig, to define the beans for each data source. These configuration classes contain the necessary settings to create the connections, and the appropriate entity manager factories and transaction managers to allow database operations. The @Primary annotation designates a primary bean among multiple beans of the same type. This is critical for situations where Spring needs to make a choice from several possible components, it helps resolve ambiguity.
Creating a Main Application Class and Controller
The main application class, often annotated with @SpringBootApplication, serves as the entry point for the application. A controller class is implemented to handle HTTP requests, fetching data from the various databases. This class defines endpoints that clients can use to interact with the application. For each database, the controller will leverage service classes, which in turn interacts with Data Access Objects (DAOs), to handle the database operations. The DAO layer acts as an abstraction, providing a clean interface for working with the database without needing to be concerned with the specifics of the database technology or connection handling.
Testing the Application
After setting up everything, the application is ready to be tested. After running the Spring Boot application, you can use tools like Postman to make HTTP requests to the controller endpoints and verify that the application is correctly retrieving data from the appropriate databases. This process involves sending requests to specific URLs, which trigger the controller logic. The controller, after receiving the request, will call the service classes and then the DAO classes, to query and retrieve data from the respective databases, based on the endpoint that was called.
Conclusion
This article has provided a conceptual overview of managing multiple data sources in a Spring Boot application. The process involves careful configuration of data sources, definition of entity models, setting up Spring beans for each data source, and implementation of controllers to handle client requests and retrieve data from the specified databases. The approach promotes modularity and maintainability, making it easier to manage complex applications with multiple data storage needs. The use of well-defined layers (controllers, services, DAOs) promotes code organization and separation of concerns. While the example used H2 databases, the same principles can be applied to other database systems by changing the database connection URLs and drivers. Remember that error handling and appropriate security measures are crucial for a production-ready application.