How to configure multiple datasources when using SpringBoot
When use springboot, we often configure one datasource ,eg, mysql or oracle, but,If we want to
use multiple datasources in a springboot project, how to code ? The answer is as follows.
1. setup mulitiple databases for test
Here, we assume you want to use two different databases of mysql in one project, we setup two databases in
mysql like this:
database:test contains one table named TBL_USERS,which stores all users.
TBL_USERS sql DDL is:
database:test2 contains one table named TBL_DEPARTS,which stores all departments.
TBL_DEPARTS sql DDL is:
You should insert some data in the tables for test.
2. Setup springboot project for demo
pom.xml
Here we use springboot 1.4.3, the latest release. Then we define the dependency ,includes
mysql,spring-boot-starter-jdbc and sprint-boot-starter-test. These are the minimal dependencies.
configure the springboot application.properties
define domain objects
User.java
contains following properties
Department.java
contains following properties
Define the DataSource beans and JdbcTemplate Beans
This is the core part. You must define some spring-beans to use multiple datasources.
MultiDatasourceConfig.java
Here we define two datasources named dsMaster and dsSecondary, then we defined two jdbcTemplate
object using the two datasources. Be careful the datasource prefix must match the application.properites
names.
Use the datasources to query from different databases
Firstly ,we autowire two jdbcTemplate objects
Then we use the objects to do the query:
Query from the datasource1: dsMaster
Query from the datasource2: dsSecondary
3. Test
Now we use the springboot unittest framework to test the upper settings and codes.
TestUserDao.java
We define a TestUserDao.java in the test source folder as follows.
You must use the @RunWith(SpringRunner.class) and @SpringBootTest to let the unittest run with springboot.
Here we define two testcases, one testcase for one datasource. Here is the result:
All the above complete project codes is uploaded to github ,check it by goto example sourcecodes.
You can find detail documents about the springboot using multiple datasources here: