1.功能介绍

在实际的开发中,同一个项目中使用多个数据源是很常见的场景。最近在学习的过程中使用注解的方式实现了一个Springboot项目多数据源的功能。具体实现方式如下。

2.在application.properties中添加多数据源配置

添加多个数据源和mapper文件路径配置,此配置用于基于java的配置数据源中使用。

#数据库配置

spring.datasource.demo.user.url=jdbc:mysql://xxx.xx.xx.xx:3306/demo-user

spring.datasource.demo.user.username=xxxx

spring.datasource.demo.user.password=xxxx

spring.datasource.demo.user.driver-class-name=com.mysql.jdbc.Driver

spring.datasource.demo.server.url=jdbc:mysql://xxx.xx.xx.xx:3306/springbootdemo

spring.datasource.demo.server.username=xxxx

spring.datasource.demo.server.password=xxxx

spring.datasource.demo.server.driver-class-name=com.mysql.jdbc.Driver

#mapper文件的路径

mybatis.demo.server.mapper-location=classpath*:mapper/demo-server/*.xml

mybatis.demo.user.mapper-location=classpath*:mapper/demo-user/*.xml

3.基于java的方式实现数据库配置

配置类图如下:

其中DemoUserDbConfig类源代码如下:

其中Configuration注解表识此类为Spring的配置类。

MapperScan注解中的basePackages、annotationClass、sqlSessionTemplateRef用于配置此数据库链接扫描com.example包中所有注解为DemoUserMapper的接口。

@Configuration

@MapperScan(basePackages = {"com.example"},annotationClass = DemoUserMapper.class,

sqlSessionTemplateRef = "demoUserTemplate")

public class DemoUserDbConfig extends AbstractDbConfig {

@Value("${spring.datasource.demo.user.url}")

private String url;

@Value("${spring.datasource.demo.user.username}")

private String userName;

@Value("${spring.datasource.demo.user.password}")

private String password;

@Value("${spring.datasource.demo.user.driver-class-name}")

private String driveClassName;

@Value(value = "${mybatis.demo.user.mapper-location}")

private String mapperLocation;

@Bean(name = "demoUser")

public DataSource secondaryDataSource() {

return dataSourceFactory(driveClassName, url, userName, password);

}

@Bean(name = "demoUserTemplate")

public SqlSessionTemplate demoUserSqlTemplate() throws Exception {

return new SqlSessionTemplate((sqlSessionFactory(secondaryDataSource(), mapperLocation)));

}

@Bean

@Qualifier("demoUserTransaction")

public PlatformTransactionManager demoUserTransaction() {

return new DataSourceTransactionManager(secondaryDataSource());

}

}

其中AbstractDatasource设置了通用的方法,源代码如下:

public abstract class AbstractDbConfig {

protected SqlSessionFactory sqlSessionFactory(DataSource dataSource, String mapperLocation) throws Exception {

SqlSessionFactoryBean factoryBean = new SqlSessionFactoryBean();

factoryBean.setDataSource(dataSource);

ResourcePatternResolver resourceResolver = new PathMatchingResourcePatternResolver();

Resource[] resource= resourceResolver.getResources(mapperLocation);

factoryBean.setMapperLocations(resource);

return factoryBean.getObject();

}

protected DataSource dataSourceFactory(String driveClassName, String url, String userName, String password){

DruidDataSource datasource = new DruidDataSource();

datasource.setDriverClassName(driveClassName);

datasource.setUrl(url);

datasource.setUsername(userName);

datasource.setPassword(password);

datasource.setMaxActive(20);

datasource.setInitialSize(20);

return datasource;

}

}

使用相同的方法定义其他数据源。

4.定义接口和mapper文件

分别定义连接demo-user数据库和springbootdemo数据库的mapper文件。连接demo-user数据库的接口如下,使用DemoUserMapper注解表识。

@DemoUserMapper

public interface UserDao {

/**

* 返回所有的dictionary列表

*

* @return 所有的dictionary列表

*/

List list();

}

mapper文件如下:

SELECT `name` FROM `user`

定义读取springbootdemo数据库的接口,代码如下。使用DemoServerMapper注解表识

@DemoServerMapper

public interface DictionaryDao {

/**

* 返回所有的dictionary列表

*

* @return 所有的dictionary列表

*/

List list();

/**

* 查询此key下的所有子节点

*

* @param key 数据字典key

* @return 返回key所有的子节点列表

*/

List listChildrenByKey(String key);

/**

* 插入数据到数据库

*

* @param dictionary

*/

void insert(Dictionary dictionary);

}

mapper文件代码如下:

SELECT * FROM `dictionary`

SELECT * FROM dictionary where parent_id= (select id from dictionary where dict_key= #{key})

delete from dictionary where id = #{id}

INSERT INTO `dictionary`(`dict_key`,`dict_value`,`parent_id`,`description`)

VALUES(#{dictKey}, #{dictValue}, #{parentId}, #{description})

5.定义注解

定义DemoUserMapper和DemoServerMapper注解,分别作为使用demo-user和springbootdemo数据库的表识。

定义代码如下:

@Documented

@Retention(RetentionPolicy.RUNTIME)

@Target(ElementType.TYPE)

@Component

@Mapper

public @interface DemoServerMapper {

/**

* The value may indicate a suggestion for a logical component name,

* to be turned into a Spring bean in case of an autodetected component.

* @return the suggested component name, if any (or empty String otherwise)

*/

String value() default "";

}

@Documented

@Retention(RetentionPolicy.RUNTIME)

@Target(ElementType.TYPE)

@Component

@Mapper

public @interface DemoUserMapper {

/**

* The value may indicate a suggestion for a logical component name,

* to be turned into a Spring bean in case of an autodetected component.

* @return the suggested component name, if any (or empty String otherwise)

*/

String value() default "";

}

6.使用单元测试验证配置

编写单元测试代码如下:

@RunWith(SpringRunner.class)

@SpringBootTest

public class MultiDatasourceApplicationTests {

@Autowired

private DictionaryDao dictionaryDao;

@Autowired

private UserDao userDao;

@Test

public void contextLoads() {

System.out.println(dictionaryDao.list());

System.out.println("===================");

System.out.println(userDao.list());

}

}

java spring多数据源配置文件_基于注解实现SpringBoot多数据源配置相关推荐

  1. java spring多数据源配置文件_深入理解spring多数据源配置

    项目中我们经常会遇到多数据源的问题,尤其是数据同步或定时任务等项目更是如此.多数据源让人最头痛的,不是配置多个数据源,而是如何能灵活动态的切换数据源.例如在一个spring和hibernate的框架的 ...

  2. java元婴期(18)----java进阶(spring(2)----DI(依赖注入)基于注解的IOC与DI配置properties)

    1.依赖注入的概念 依赖注入:Dependency Injection.它是spring框架核心ioc的具体实现. 我们的程序在编写时,通过控制反转,把对象的创建交给了spring,但是代码中不可能出 ...

  3. java oauth sso 源码_基于Spring Security Oauth2的SSO单点登录+JWT权限控制实践

    概 述 在前文<基于Spring Security和 JWT的权限系统设计>之中已经讨论过基于 Spring Security和 JWT的权限系统用法和实践,本文则进一步实践一下基于 Sp ...

  4. java实现系统参数的存储_基于ZooKeeper,Spring设计实现的参数系统

    一.简介 基于ZooKeeper服务端.ZooKeeper Java客户端以及Spring框架设计的用于系统内部进行参数维护的系统. 二.设计背景 在我们日常开发的系统内部,开发过程中最常见的一项工作 ...

  5. java自定义配置文件_基于java读取并引用自定义配置文件

    基于java读取并引用自定义配置文件 首先在resources目录创建自定义的配置文件 配置文件的格式: 写工具类,得到配置参数 import java.io.IOException; import ...

  6. SpringAOP描述及实现_AspectJ详解_基于注解的AOP实现_SpringJdbcTemplate详解

    AOP AOP特点: 面向切面编程, 利用AOP对业务逻辑的各个部分进行抽取公共代码, 降低耦合度, 提高代码重用性, 同时提高开发效率. 采取横向抽取, 取代传统纵向继承体系重复性代码 解决事务管理 ...

  7. boot spring 接口接收数据_基于 Spring Boot 实现 Restful 风格接口,实现增删改查功能...

    优质文章,及时送达 Spring Boot介绍 Spring Boot是由Pivotal团队提供的全新框架,其设计目的是用来简化新Spring应用的初始搭建以及开发过程.该框架使用了特定的方式来进行配 ...

  8. spring IOC容器 Bean 管理——基于注解方式

    IOC 操作 Bean 管理(基于注解方式) 1.什么是注解 ​ (1)注解是代码特殊标记,格式:@注解名称(属性名称=属性值, 属性名称=属性值-) ​ (2)使用注解,注解作用在类上面,方法上面, ...

  9. java中ssm付款代码_基于Java+SSM的网上订餐系统、基于JavaWeb的网上订餐系统

    需求分析 基于Java+SSM框架实现一个校园点餐系统,包括用户端和管理员端; 前台主要功能有用户注册, 用户登录, 我的购物车.我的订单.商品评论.校园资讯等; 管理员端主要功能有:用户管理.商品管 ...

最新文章

  1. python列表的排序方法_pythonlist排序的两种方法及实例
  2. 使用LCC网络补偿设计无线功率系统
  3. 手机端实现点击复制功能
  4. 用python的matplotlib画标准正态曲线
  5. LDAP命令介绍---dsconfig
  6. 理解Linux中断 (3)【转】
  7. java赋值父类_java新手求助super和set给父类赋值!
  8. BAT架构师推荐的9本程序员技术进阶图书,大家看过多少?
  9. java io中file类_java中IO常见的IO流和file类理论总结
  10. VBS脚本病毒原理分析与防范
  11. 保存电脑上的屏保图片
  12. 一行让电脑说话的代码
  13. atapi.sys 蓝屏 难度系数☆☆☆ ...
  14. C#番外篇-SpinWait
  15. C 通过四个点计算两条直线的交点
  16. 显示Java国家列表
  17. 电车要迎来大爆发?华州电车的额外补贴要来了
  18. Docker入门教程 Part 1 基础概念 - 镜像、容器、仓库
  19. 实例学习Ansible系列:颜色与设定
  20. KafkaConsumer is not safe for multi-threaded access

热门文章

  1. 【PL/SQL】PL/SQL语言基础
  2. 【Oracle】查询当前SCN
  3. 利用nginx 反向代理解决跨域问题
  4. 记Outlook插件与Web页面交互的各种坑 (含c# HttpWebRequest 连接https 的完美解决方法)
  5. The servlet name already exists.解决方法
  6. 微服务架构的分布式事务解决方案(Dubbo分布式事务处理)
  7. 原因是出现以下错误: 80040154 没有注册类 (异常来自 HRESULT:0x80040154 (REGDB_E_CLASSNOTREG))
  8. 中心/设置地图缩放以覆盖所有可见的标记?
  9. 用于检测浏览器语言偏好的JavaScript
  10. 如何在Node.js中处理POST数据?