How to configure multi Postgres DataSources with Springboot

In the tutorial, JavaSampleApproach will guide you how to configure multi Postgres DataSources with Spring Boot.

I. Technologies for Multi Postgres Datasources tutorial

– Java 1.8
– Maven 3.3.9
– Spring Tool Suite – Version 3.8.1.RELEASE

II. Overview
1. Project Structure

springboot configure multi postgres datasources

Model: Customer.java
Dao Layer: CustomerDao.java is an interface and CustomerDaoImpl.java is an implementation of CustomerDao.java.
DataSource: Configured in DataSourceBeans.java
application.properties: used to define properties of data sources.

2. Step to do

– Create SpringBoot project.
– Setup Postgres Databases.
– Configure Datasource properties in application.properties file.
– Create a Model class.
– Build Dao Layer.
– Build a Client.

III. Practice
1. Create SpringBoot project.

Open Spring Tool Suite, on main menu, choose File->New->Spring Starter Project, input project’s info.
Press Next, then press Finish, a Spring Boot project will be created.

Open pom.xml file, add JDBC & PostgreSQL dependencies:

2. Setup Postgres Databases.

Create 2 PostgreSQL databases: db1 & db2
In each database, create a customer table with sql script:

3. Configure Datasource properties in application.properties file

Open application.properties, configure as below:
– Datasource properties for PostgreSQL db1

– Datasource properties for PostgreSQL db2:

4. Create a Model class.

5. Build Dao Layer.

– Configure DataSource Beans:

– Create CustomerDao.java interface

– Implement Customer Dao:
For db1 database, create Db1CustomerDao.java

For db2 database, create Db2CustomerDao.java

6. Build a Client.

IV. Sourcecode

SpringBootConfigMultiDataSources


Related Posts



Got Something To Say:

Your email address will not be published. Required fields are marked *

*