springboot 配置多数据源实例代码(分包方式)
1、数据库
下面是实例中用到的两个数据库

2、pom与yml
2.1、pom中的依赖部分
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>2.2.0</version>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<optional>true</optional>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<scope>runtime</scope>
</dependency>
2.2、yml数据库配置部分
spring:
datasource:
db1: # 数据源1
jdbc-url: jdbc:mysql://localhost:3306/test?characterEncoding=utf8&useUnicode=true&useSSL=false&serverTimezone=GMT%2B8
username: root
password: 123456
driver-class-name: com.mysql.cj.jdbc.Driver
db2: # 数据源2
jdbc-url: jdbc:mysql://192.168.60.1:3306/test?characterEncoding=utf8&useUnicode=true&useSSL=false&serverTimezone=GMT%2B8
username: root
password: 123456
driver-class-name: com.mysql.cj.jdbc.Driver
代码文件结构

3、数据源配置类 DataSourceConfig
3.1、DataSourceConfig1.java
注意可能要修改的地方
包名:com.example.springdemo01.mapper.db1
mapping目录:classpath:mapping/db1/.xml
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.boot.jdbc.DataSourceBuilder;
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 javax.sql.DataSource;
@Configuration
@MapperScan(basePackages = "com.example.springdemo01.mapper.db1", sqlSessionFactoryRef = "db1SqlSessionFactory")
public class DataSourceConfig1 {
@Primary // 表示这个数据源是默认数据源, 这个注解必须要加,因为不加的话spring将分不清楚那个为主数据源(默认数据源)
@Bean("db1DataSource")
@ConfigurationProperties(prefix = "spring.datasource.db1") //读取application.yml中的配置参数映射成为一个对象
public DataSource getDb1DataSource(){
return DataSourceBuilder.create().build();
}
@Primary
@Bean("db1SqlSessionFactory")
public SqlSessionFactory db1SqlSessionFactory(@Qualifier("db1DataSource") DataSource dataSource) throws Exception {
SqlSessionFactoryBean bean = new SqlSessionFactoryBean();
bean.setDataSource(dataSource);
// mapper的xml形式文件位置必须要配置,不然将报错:no statement (这种错误也可能是mapper的xml中,namespace与项目的路径不一致导致)
bean.setMapperLocations(new PathMatchingResourcePatternResolver().getResources("classpath*:mapping/db1/*.xml"));
return bean.getObject();
}
@Primary
@Bean("db1SqlSessionTemplate")
public SqlSessionTemplate db1SqlSessionTemplate(@Qualifier("db1SqlSessionFactory") SqlSessionFactory sqlSessionFactory){
return new SqlSessionTemplate(sqlSessionFactory);
}
}
3.2、DataSourceConfig2.java
注意可能要修改的地方
包名:com.example.springdemo01.mapper.db2
mapping目录:classpath:mapping/db2/.xml
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.boot.jdbc.DataSourceBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import javax.sql.DataSource;
@Configuration
@MapperScan(basePackages = "com.example.springdemo01.mapper.db2", sqlSessionFactoryRef = "db2SqlSessionFactory")
public class DataSourceConfig2 {
@Bean("db2DataSource")
@ConfigurationProperties(prefix = "spring.datasource.db2")
public DataSource getDb1DataSource(){
return DataSourceBuilder.create().build();
}
@Bean("db2SqlSessionFactory")
public SqlSessionFactory db1SqlSessionFactory(@Qualifier("db2DataSource") DataSource dataSource) throws Exception {
SqlSessionFactoryBean bean = new SqlSessionFactoryBean();
bean.setDataSource(dataSource);
bean.setMapperLocations(new PathMatchingResourcePatternResolver().getResources("classpath*:mapping/db2/*.xml"));
return bean.getObject();
}
@Bean("db2SqlSessionTemplate")
public SqlSessionTemplate db1SqlSessionTemplate(@Qualifier("db2SqlSessionFactory") SqlSessionFactory sqlSessionFactory){
return new SqlSessionTemplate(sqlSessionFactory);
}
}
4、dao层
UserDao.java (db1包下)
import org.springframework.stereotype.Repository;
@Repository
public interface UserDao {
String getName();
}
UserDao2.java (db2包下)
import org.springframework.stereotype.Repository;
@Repository
public interface UserDao2 {
String getName();
}
5、xml文件
user.xml (mapping/db1目录下)
<?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.example.springdemo01.mapper.db1.UserDao">
<select id="getName" resultType="String">
select name from user where id = 1;
</select>
</mapper>
user.xml (mapping/db1目录下)
<?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.example.springdemo01.mapper.db2.UserDao2">
<select id="getName" resultType="String">
select name from user where id = 1;
</select>
</mapper>
6、service与controller
service接口
public interface UserService {
String getName();
}
service实现层 (注意修改导入的dao层、service接口包名)
import com.example.springdemo01.mapper.db1.UserDao;
import com.example.springdemo01.mapper.db2.UserDao2;
import com.example.springdemo01.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
@Service
public class UserServiceImpl implements UserService {
@Autowired
UserDao dao1;
@Autowired
UserDao2 dao2;
@Override
public String getName() {
return dao1.getName()+","+dao2.getName();
}
}
UserController.java
import com.example.springdemo01.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class UserController {
@Autowired
UserService service;
@GetMapping("/get")
public String names(){
return service.getName();
}
}
7、测试

springboot 配置多数据源实例代码(分包方式)的更多相关文章
- SpringBoot配置多数据源时遇到的问题
SpringBoot配置多数据源 参考代码:Spring Boot 1.5.8.RELEASE同时配置Oracle和MySQL 原作者用的是1.5.8版本的SpringBoot,在升级到2.0.*之后 ...
- springboot配置Druid数据源
springboot配置druid数据源 Author:SimpleWu springboot整合篇 前言 对于数据访问层,无论是Sql还是NoSql,SpringBoot默认采用整合SpringDa ...
- springboot 配置多数据源
1.首先在创建应用对象时引入autoConfig package com; import org.springframework.boot.SpringApplication; import org. ...
- Tomcat配置JNDI数据源的三种方式-转-http://blog.51cto.com/xficc/1564691
第一种,单个应用独享数据源 就一步,找到Tomcat的server.xml找到工程的Context节点,添加一个私有数据源 Xml代码 <Context docBase="WebA ...
- 配置quartz数据源的三种方式
如果是使用了JDBC JobStore或JobStoreCMT获得持久的Job时,就要配置相关的数据源了. 方式一:使用quartz.properties文件,这时只需要在property文件中增加如 ...
- Oracle rac配置Weblogic数据源(实例名及URL的选择)
这几天,应用程序后台一直报无法取得连数据库接池.但之前从来没有这个问题,迁移到Weblogic后才发生. 之后据了解,我们服务器上的Oracle 10G 是 RAC 的,即有两个节点. 两个节点 IP ...
- springboot 配置多数据源 good
1.首先在创建应用对象时引入autoConfig package com; import org.springframework.boot.SpringApplication; import org. ...
- 【转】在Tomcat配置JNDI数据源的三种方式
在我过去工作的过程中,开发用服务器一般都是Tomcat 数据源的配置往往都是在applicationContext.xml中配置一个dataSource的bean 然后在部署时再修改JNDI配置 我猜 ...
- 在Tomcat配置JNDI数据源的三种方式
最近使用到了在tomcat下配置数据源的内容,在这里转载一篇文章记录下 转载自: http://blog.csdn.net/dyllove98/article/details/7706218 在我过去 ...
随机推荐
- 记一个非常诡异的关于 shared_ptr 的 bug
问题描述 今天写项目的时候遇见一个特别诡异的 bug,体现在在执行某条语句时,程序会莫名崩溃,并且给出的错误信息也非常难懂,只有一个malloc(): invalid size (unsorted)错 ...
- netty中使用protobuf实现多协议的消息
在我们使用 netty 的过程中,有时候为了高效的传输数据,经常使用 protobuf 进行数据的传输,netty默认情况下为我们实现的 protobuf 的编解码,但是默认的只能实现单个对象的编解码 ...
- 为什么用于开关电源的开关管一般用MOS管而不是三极管
区别: 1.MOS管损耗比三极管小,导通后压降理论上为0. 2.MOS管为电压驱动型,只需要给电压即可,意思是即便串入一个100K的电阻,只要电压够,MOS管还是能够导通. 3.MOS管的温度特性要比 ...
- Hash算法:双重散列
双重散列是线性开型寻址散列(开放寻址法)中的冲突解决技术.双重散列使用在发生冲突时将第二个散列函数应用于键的想法. 此算法使用: (hash1(key) + i * hash2(key)) % TAB ...
- 单源最短路径算法:迪杰斯特拉 (Dijkstra) 算法(一)
一.算法介绍 迪杰斯特拉算法(英语:Dijkstra's algorithm)由荷兰计算机科学家艾兹赫尔·迪杰斯特拉在1956年提出.迪杰斯特拉算法使用了广度优先搜索解决赋权有向图的单源最短路径问题. ...
- mybatis竟然报"Invalid value for getInt()"
目录 背景 场景 初探 再探 结局 背景 使用mybatis遇到一个非常奇葩的问题,错误如下: Cause: org.apache.ibatis.executor.result.ResultMapEx ...
- Python import urllib2 ImportError: No module named 'urllib2'
python3 import urllib2 import urllib2 ImportError: No module named 'urllib2' python3.3里面,用urllib.req ...
- 清除行列 牛客网 程序员面试金典 C++ Python
清除行列 牛客网 程序员面试金典 C++ Python 题目描述 请编写一个算法,若N阶方阵中某个元素为0,则将其所在的行与列清零. 给定一个N阶方阵int[]mat和矩阵的阶数n,请返回完成操作后的 ...
- 01_WPF概述
目录 Windows 图形演化 高级API 分辨率无关性 WPF体系结构 我的微信公众号 Windows 图形演化 在 WPF 之前,windows 开发一直使用本质上相同的显示技术.每个传统 win ...
- spark structured-streaming 最全的使用总结
一.spark structured-streaming 介绍 我们都知道spark streaming 在v2.4.5 之后 就进入了维护阶段,不再有新的大版本出现,而且 spark strea ...