本文结合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. 15、vue项目封装axios并访问接口

    1.在src下新建util文件夹,在util下新建request.js文件: 封装axios: import axios from 'axios' import QS from 'qs'; // im ...

  2. RabbitMQ基本概念(四)-服务详细配置与日常监控管理

    RabbitMQ服务管理 启动服务:rabbitmq-server -detached[ /usr/local/rabbitmq/sbin/rabbitmq-server -detached ] 查看 ...

  3. rsync异常处理

    实验环境: centos7.6 实验目的:    错误的思考,在目标端执行rsync拉取源端文件,源端也必须存在rsync命令,目的用于差异比对实现增量传输! 01.执行rsync命令不存在 02.执 ...

  4. likely和unlikely是如何对代码的优化?

             在执行if判断时,可以使用GCC提供了__builtin_expect对代码进行优化,可以提高代码的运行速度,参考GCC手册的"3.10 Options That Cont ...

  5. 如何为scratch3.0创建一个独立的页面或窗体

    很多人都利用GIT上的scratch3.0做开发,但是苦于有些定制需要个性化开发但是不知道如何动手.本篇文章来做好普及工作吧. 首先需要完成事项如下: 1.需要进行modal定义 2.新增窗口的UI界 ...

  6. rhel6.2配置在线yum源

    由于 redhat的yum在线更新是收费的,如果没有注册的话不能使用,如果要使用,需将redhat的yum卸载后,重启安装,再配置其他源. 本文包括配置本地源及第三方源.第三方源包括:网易,epel, ...

  7. 项目Beta冲刺(团队)——总结篇

    项目Beta冲刺(团队)--总结篇 格式描述 课程名称:软件工程1916|W(福州大学) 作业要求:项目Beta冲刺(团队) 团队名称:为了交项目干杯 作业目标:Beta冲刺总结 团队信息 队员学号 ...

  8. datagrid 溢出文本显示省略号 转载

    http://www.jeasyuicn.com/?sort=3 .datagrid-cell, .datagrid-cell-group, .datagrid-header-rownumber, . ...

  9. python基础语法8 叠加装饰器,有参装饰器,wraps补充,迭代器

    叠加装饰器: 叠加装饰器 - 每一个新的功能都应该写一个新的装饰器 - 否则会导致,代码冗余,结构不清晰,可扩展性差 在同一个被装饰对象中,添加多个装饰器,并执行. @装饰1 @装饰2 @装饰3 de ...

  10. Fiddler实现篡改接口请求和返回数据

    步骤如下: 点击rules->Automatic Breakpoints,在这个选项下,我们可以看到三个可选项: Before Requests:在请求发出前拦截请求: After Reques ...