代码基于 SpringBoot + SpringDataJDBC + Mybatis 架构
介绍使用多数据源的关键的一些类:AbstractRoutingDataSource继承实现determineCurrentLookupKey方法,此方法主要返回AbstractRoutingDataSource抽象类的多数据源的Key值
提醒:这里主要提醒一下,Spring Aop(AspectJ实现)的拦截方法,@Before@After注解之类的方法的参数可以具有一个 org.aspectj.lang.JoinPoint 类型的形参,而@Around类需要是ProceedingJoinPoint此形参,不要混用(官方说明来源:https://docs.spring.io/spring/docs/5.2.6.RELEASE/spring-framework-reference/core.html#aop-ataspectj-advice-params)
首先展示下配置文件:application.yml
spring: datasource: one: username: root password: root jdbc-url: jdbc:mariadb://localhost:3306/myschool driver-class-name: org.mariadb.jdbc.Driver two: username: root password: root jdbc-url: jdbc:mariadb://localhost:3306/myschool driver-class-name: org.mariadb.jdbc.Driver
配置多个数据源:
@Bean(value = "db1")
@ConfigurationProperties(prefix = "spring.datasource.one")
public HikariDataSource dataSource() {
HikariDataSource dataSource = new HikariDataSource();
return dataSource;
}
@Bean(value = "db2")
@ConfigurationProperties(prefix = "spring.datasource.two")
public HikariDataSource dataSource2() {
HikariDataSource dataSource = new HikariDataSource();
return dataSource;
}
下面是多数据源的配置:
动态数据源实现如下:
获取数据源的目标位置:DataSourceTransactionManager类的doBegin方法
具体可以下载Demo试试:https://github.com/starSmallDream/MySpringDataJdbcAndMybatisByManyDataSource.git