本文结合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. pandas-17 关于nan的处理

    pandas-17 关于nan的处理 在pandas中有个另类的存在就是nan,解释是:not a number,不是一个数字,但是它的类型确是一个float类型.numpy中也存在关于nan的方法, ...

  2. sql语句技巧

    应用场景:当sql 语句中where后面的条件字段为空的时候,条件不存在 eg:根据传入的参数,从student表中查询数据,参数包含姓名(name 必有),年龄(age 不一定有),性别(gende ...

  3. 面试题:什么叫B树

    B是balanced的意思 是在二叉查找树  树的基础上增加了平衡的性质   导致它不是  二叉树了,变成了多叉树,但是叉几路又有了限制  否则怎么平衡呢 一棵m阶B树(balanced tree o ...

  4. WPE 过滤器 滤镜 用法

    过滤所有数值匹配的数据包,并修改指定的bit位 打开游戏 打开WPE 附加游戏进程 选项配置 用来配置抓取发送和接收包类型 先抓取发送包,也就是游戏中主动发给服务器的包 点击开始抓包 输入喊话内容 分 ...

  5. 一次 Young GC 的优化实践(FinalReference 相关)

    本文转载自公众号:涤生的博客,阅读时间大约需要11分钟.涤生的文章看起来跟破案一样,很精彩,很有启发. 前言 博客已经好久没有更新了,主要原因是 18 年下半年工作比较忙,另外也没有比较有意思的题材, ...

  6. python写入csv文件时的乱码问题

    今天在使用python的csv库将数据写入csv文件时候,出现了中文乱码问题,解决方法是在写入文件前,先指定utf-8编码,如下: import csv import codecs if __name ...

  7. iView学习笔记(三):表格搜索,过滤及隐藏列操作

    iView学习笔记(三):表格搜索,过滤及隐藏某列操作 1.后端准备工作 环境说明 python版本:3.6.6 Django版本:1.11.8 数据库:MariaDB 5.5.60 新建Django ...

  8. Django如何渲染markdown

    本文已默认你已经好创建Django工程和App. 依赖包 pip install markdown django-markup bleach bleach-whitelist 示例代码 your_ap ...

  9. python应用-21根火柴游戏

    """ 21跟火柴 """ from random import randint def main(): total=21 while to ...

  10. hive删除数据(转)

    转自:https://www.cnblogs.com/linn/p/6196293.html 按分区删除: ALTER TABLE test1  DROP PARTITION (dt='2016-04 ...