本文结合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. hello world之vivado程序解决方法

    体验米尔zynq系列Z-turn Board单板时,我开始用vivado.在安装vivad工程中出了一些问题,经过不懈的重新安装,终于成功了. 下面分享我用vivado设计hello world程序: ...

  2. 微信小程序必知相关知识

    微信小程序必知相关知识 1 请谈谈微信小程序主要目录和文件的作用? project.config.json 项目配置文件,用得最多的就是配置是否开启https校验: App.js 设置一些全局的基础数 ...

  3. React Hooks --- useState 和 useEffect

    首先要说的一点是React Hooks 都是函数,使用React Hooks,就是调用函数,只不过不同的Hooks(函数)有不同的功能而已.其次,React Hooks只能在函数组件中使用,函数组件也 ...

  4. Android常用五种布局

    1. FrameLayout(框架布局) 这个布局可以看成是墙脚堆东西,有一个四方的矩形的左上角墙脚,我们放了第一个东西,要再放一个,那就在放在原来放的位置的上面,这样依次的放,会盖住原来的东西.这个 ...

  5. Java DbUtils简介

    Dbutils,db utils,顾名思义,是一个数据库工具,体积很小,算是一个dao层的小框架. DbUtils是Apache的开源项目,对JDBC进行了轻量级封装,极大地简化了JDBC编程. Db ...

  6. InvalidOperationException: No file provider has been configured to process the supplied file.

    现在有一个api, 提供图片的下载,如下代码,,调试出现 InvalidOperationException: No file provider has been configured to proc ...

  7. 阿里云ECS-使用putty产品psftp工具上传下载

    本人windows10,安装了winscp3,原本可以简单易用,但天空不作美,死活不让我连接,无奈,只能换命令行方式, 好在,putty提供了一个小工具,psftp,不过,需要去官网下载完整版才有哦, ...

  8. python url合并与分离

     #!/bin/python3 from urllib import parse parse.urlsplit() 将url分为6个部分,返回一个包含6个字符串项目的元组:协议.位置.路径.参数.查询 ...

  9. Python 去除文件中的空行

    def clear_space(): with open("test","r",encoding="utf-8") as fr: for l ...

  10. 实战 MySQL 8.0.17 Clone Plugin(转)

    背景 很神奇,5.7.17 和 8.0.17,连续两个17小版本都让人眼前一亮.前者加入了组复制(Group Replication)功能,后者加入了克隆插件(Clone Plugin)功能.今天我们 ...