本文结合SpringBoot + MyBatis + MySql进行多数据源配置,DataSource信息采用自定义dataSource.properties进行配置。

1.文件结构如下:

2.1 pom依赖:

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.stu</groupId>
<artifactId>HelloMybatis</artifactId>
<version>0.0.1-SNAPSHOT</version>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.0.3.RELEASE</version>
</parent>
<dependencies>
<!-- web项目 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<!-- freemarker -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-freemarker</artifactId>
</dependency>
<!-- mysql -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
</dependency>
<!-- 数据源 -->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid</artifactId>
<version>1.0.19</version>
</dependency>
<!-- mybatis -->
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>1.3.0</version>
</dependency>
</dependencies>
</project>
2.2 启动类:

package com.stu;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@SpringBootApplication
@RestController
public class MybatisApplication {
public static void main(String[] args) {
SpringApplication.run(MybatisApplication.class, args);
}
@RequestMapping("/app")
public String hello() {
return "ok";
}
}
2.3 properties配置文件:

2.3.1 application.properties

server.port=8080
server.servlet.context-path=/mybatis
spring.freemarker.prefix=/views
spring.freemarker.suffix=.html
2.3.2 dataSource.properties

spring.datasource.base.url=jdbc:mysql://localhost:3306/test1
spring.datasource.base.username=root
spring.datasource.base.password=root
spring.datasource.base.driverClassName=com.mysql.jdbc.Driver

spring.datasource.slave.url=jdbc:mysql://localhost:3306/test2
spring.datasource.slave.username=root
spring.datasource.slave.password=root
spring.datasource.slave.driverClassName=com.mysql.jdbc.Driver
2.4 读取properties文件,并封装成实体类

2.4.1 base数据源配置实体类

package com.stu.config;

import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.PropertySource;
import org.springframework.stereotype.Component;
@Component
/*指定配置文件名,默认从classpath下寻找该文件,也就是等同于classpath:dataSource.properties
* 可以指定多个文件
*/
@PropertySource(value = { "dataSource.properties" })
/*
* 指定前缀,读取的配置信息项必须包含该前缀,且除了前缀外,剩余的字段必须和实体类的属性名相同,
* 才能完成银映射
*/
@ConfigurationProperties(prefix = "spring.datasource.base")
public class DB1Config {
private String url;
private String username;
private String password;
private String driverClassName;
getter/setter...

}
2.4.2 slave数据源配置实体类

package com.stu.config;

import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.PropertySource;
import org.springframework.stereotype.Component;

@Component
@PropertySource(value = { "dataSouce.properties" })
@ConfigurationProperties(prefix = "spring.datasource.slave")
public class DB2Config {
private String url;
private String username;
private String password;
private String driverClassName;
setter/getter...

}
2.5 数据源配置类:

2.5.1 DB1Configuration

package com.stu.config;

import javax.sql.DataSource;

import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.SqlSessionTemplate;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;

import com.alibaba.druid.pool.DruidDataSource;

@Configuration
//只从com.stu.dao包下读取dao文件,并且该报下的dao使用本datasource
@MapperScan(basePackages = "com.stu.dao", sqlSessionTemplateRef = "baseSqlSessionTemplate")
public class DB1Configuration {
@Bean(name = "baseDataSource")
//对于多数据源,必须制定primary,否则报错有2个datasource,并且,只能制定一个primary
@Primary
//从DB1Config从获取配置信息
public DataSource setDataSource(DB1Config dbc) {
DruidDataSource ds = new DruidDataSource();
ds.setUrl(dbc.getUrl());
ds.setUsername(dbc.getUsername());
ds.setPassword(dbc.getPassword());
ds.setDriverClassName(dbc.getDriver());
return ds;
}

@Bean(name = "baseSqlSessionFactory")
@Primary
public SqlSessionFactory setSqlSessionFactory(@Qualifier("baseDataSource") DataSource dataSource) throws Exception {
SqlSessionFactoryBean bean = new SqlSessionFactoryBean();
bean.setDataSource(dataSource);
//指定mapper.xml文件存放位置
bean.setMapperLocations(new PathMatchingResourcePatternResolver().getResources("classpath:mapper/base/*.xml"));
return bean.getObject();
}

@Bean(name = "baseSqlSessionTemplate")
@Primary
public SqlSessionTemplate setSqlSessionTemplate(@Qualifier("baseSqlSessionFactory") SqlSessionFactory sqlSessionFactory) throws Exception {
return new SqlSessionTemplate(sqlSessionFactory);
}
}
2.5.2 DB2Configuration

package com.stu.config;
import javax.sql.DataSource;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.SqlSessionTemplate;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import com.alibaba.druid.pool.DruidDataSource;

@Configuration
//只从com.stu.test2dao包下读取dao文件,并且该报下的dao使用本datasource
@MapperScan(basePackages = "com.stu.test2dao", sqlSessionTemplateRef = "slaveSqlSessionTemplate")
public class DB2Configuration {
@Bean(name = "slaveDataSource")
@ConfigurationProperties(prefix = "spring.datasource.slave")
public DataSource setDataSource(DB2Config dbc) {
DruidDataSource ds = new DruidDataSource();
ds.setUrl(dbc.getUrl());
ds.setUsername(dbc.getUsername());
ds.setPassword(dbc.getPassword());
ds.setDriverClassName(dbc.getDriver());
return ds;
}

@Bean(name = "slaveSqlSessionFactory")
public SqlSessionFactory setSqlSessionFactory(@Qualifier("slaveDataSource") DataSource dataSource) throws Exception {
SqlSessionFactoryBean bean = new SqlSessionFactoryBean();
bean.setDataSource(dataSource);
bean.setMapperLocations(new PathMatchingResourcePatternResolver().getResources("classpath:mapper/slave/*.xml"));
return bean.getObject();
}

@Bean(name = "slaveSqlSessionTemplate")
public SqlSessionTemplate setSqlSessionTemplate(@Qualifier("slaveSqlSessionFactory") SqlSessionFactory sqlSessionFactory) throws Exception {
return new SqlSessionTemplate(sqlSessionFactory);
}
}
2.6 Mapper文件

2.6.1 userMapper.xml

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd" >
<mapper namespace="com.stu.dao.UserDao" >
<insert id="insert" parameterType="java.util.Map">
insert into user (id, name, age) values (#{id}, #{name}, #{age});
</insert>
</mapper>
2.6.2 userTest2Mapper.xml

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd" >
<mapper namespace="com.stu.test2dao.UserDao2" >
<insert id="insert" parameterType="java.util.Map">
insert into user2 (id, name, age) values (#{id}, #{name}, #{age});
</insert>
</mapper>
2.7 Dao类:

2.7.1 UserDao

package com.stu.dao;
import org.apache.ibatis.annotations.Param;
public interface UserDao {
void insert(@Param("id") Integer id, @Param("name")String name, @Param("age")Integer age);
}
2.7.2 UserDao2

package com.stu.test2dao;
import org.apache.ibatis.annotations.Param;
public interface UserDao2 {
void insert(@Param("id") Integer id, @Param("name")String name, @Param("age")Integer age);
}
2.8 Service

package com.stu.service;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.stu.dao.UserDao;
import com.stu.test2dao.UserDao2;

@Service
public class UserService {
@Autowired
private UserDao dao1;
@Autowired
private UserDao2 dao2;

public void createUser1(Integer id, String name, Integer age) {
dao1.insert(id, name, age);
}

public void createUser2(Integer id, String name, Integer age) {
dao2.insert(id, name, age);
}
}
2.9 Controller

package com.stu.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.stu.service.UserService;

@RestController
public class UserController {

@Autowired
UserService userService;

@RequestMapping("/add")
public String createUser1(Integer id, String name, Integer age) {
userService.createUser1(id, name, age);
return "ok";
}
@RequestMapping("/add2")
public String createUser2(Integer id, String name, Integer age) {
userService.createUser2(id, name, age);
return "ok";
}

————————————————

参考链接:https://blog.csdn.net/houfengfei668/article/details/79947032

     https://blog.csdn.net/qq_28060549/article/details/82077705

Spring Boot通过Configuration配置多数据源的更多相关文章

  1. Spring Boot + MyBatis + Pagehelper 配置多数据源

    前言: 本文为springboot结合mybatis配置多数据源,在项目当中很多情况是使用主从数据源来读写分离,还有就是操作多库,本文介绍如何一个项目同时使用2个数据源. 也希望大家带着思考去学习!博 ...

  2. Spring Boot整合Druid配置多数据源

    Druid是阿里开发的数据库连接池,功能强大,号称Java语言中最好的数据库连接池.本文主要介绍Srping Boot下用Druid配置多个数据源,demo环境为:Spring Boot 2.1.4. ...

  3. spring boot:用dynamic-datasource-spring-boot-starter配置多数据源访问seata(seata 1.3.0 / spring boot 2.3.3)

    一,dynamic-datasource-spring-boot-starter的优势? 1,dynamic-datasource-spring-boot-starter 是一个基于springboo ...

  4. spring boot 2.0 配置双数据源 MySQL 和 SqlServer

    参考:https://www.cnblogs.com/xiaofengfeng/p/9552816.html 安装 org.mybatis.spring.boot:mybatis-spring-boo ...

  5. spring boot + druid + mybatis + atomikos 多数据源配置 并支持分布式事务

    文章目录 一.综述 1.1 项目说明 1.2 项目结构 二.配置多数据源并支持分布式事务 2.1 导入基本依赖 2.2 在yml中配置多数据源信息 2.3 进行多数据源的配置 三.整合结果测试 3.1 ...

  6. Spring Boot 2.x Redis多数据源配置(jedis,lettuce)

    Spring Boot 2.x Redis多数据源配置(jedis,lettuce) 96 不敢预言的预言家 0.1 2018.11.13 14:22* 字数 65 阅读 727评论 0喜欢 2 多数 ...

  7. Spring Boot 2.0 配置图文教程

    摘要: 原创出处 https://www.bysocket.com 「公众号:泥瓦匠BYSocket 」欢迎关注和转载,保留摘要,谢谢! 本章内容 自定义属性快速入门 外化配置 自动配置 自定义创建 ...

  8. Spring Boot HikariCP 一 ——集成多数据源

    其实这里介绍的东西主要是参考的另外一篇文章,数据库读写分离的. 参考文章就把链接贴出来,里面有那位的代码,简单明了https://gitee.com/comven/dynamic-datasource ...

  9. Spring Boot 集成 Mybatis 实现双数据源

    这里用到了Spring Boot + Mybatis + DynamicDataSource配置动态双数据源,可以动态切换数据源实现数据库的读写分离. 添加依赖 加入Mybatis启动器,这里添加了D ...

随机推荐

  1. android中app卡顿优化问题

     所谓app卡顿原因就是在运行时出现了丢帧,还可能是UI线程被阻塞.首先来一下丢帧现象,android每16ms会对界面进行一次渲染,如果app的绘制.计算等超过了16ms那么只能等下一个16ms才能 ...

  2. Java变量常量声明和定义

    一.常量和变量 1.常量变量定义 在程序中存在大量的数据来代表程序的状态,其中有些数据在程序的运行过程中值会发生改变,有些数据在程序运行过程中值不能发生改变,这些数据在程序中分别被叫做变量和常量. 2 ...

  3. FormData使用方法详解

    FormData的主要用途有两个: 1.将form表单元素的name与value进行组合,实现表单数据的序列化,从而减少表单元素的拼接,提高工作效率. 2.异步上传文件 一.创建formData对象 ...

  4. 【Spring Cloud】Spring Cloud之整合Spring Cloud Bus以及最佳实践

    一.整合步骤 1)加入Maven坐标 <!-- actuator监控模块 --> <dependency> <groupId>org.springframework ...

  5. linux命令实现在当前文件夹下面模糊搜索文件

    在当前文件中查找包含的字符串 find . -name "*.txt" | xargs grep 'abc' ,例如:查找txt文件中包含字符串a的字符串

  6. Explorer(2019年牛客多校第八场E题+线段树+可撤销并查集)

    题目链接 传送门 题意 给你一张无向图,每条边\(u_i,v_i\)的权值范围为\([L_i,R_i]\),要经过这条边的条件是你的容量要在\([L_i,R_i]\),现在问你你有多少种容量使得你可以 ...

  7. jmeter压测学习2-linux运行jmeter环境

    前言 使用jmeter做压测的时候,在windows上不太稳定,所有一直在linux服务器上使用jmeter做压力测试. 本篇记录下linux上搭建jmeter环境,以及运行jmeter脚本,查看报告 ...

  8. 使用django的MTV开发模式返回一个网页

    1.MTV开发模式介绍 M:Models 模型(数据) 与数据组织相关的功能.组织和存储数据的方法和模式,与数据模型相关的操作. T:Templates 模板(样式) 与表现相关的所有功能.页面展示风 ...

  9. laravel 配置路由 api和web定义的路由的区别详解

    1.路由经过中间件方面不同 打开kerenl.php就可以看到区别 protected $middlewareGroups = [ 'web' => [ \App\Http\Middleware ...

  10. python应用-跑马灯

    import os import time def main(): str1='欢迎来到前锋学习Python' while True: os.system('cls') print(str1) tim ...