第九章 springboot + mybatis + 多数据源 (AOP实现)(转载)

时间:2023-03-09 05:48:48
第九章 springboot + mybatis + 多数据源 (AOP实现)(转载)

本编博客转发自:http://www.cnblogs.com/java-zhao/p/5415896.html

1、ShopDao

package com.xxx.firstboot.dao;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository; import com.xxx.firstboot.domain.Shop;
import com.xxx.firstboot.mapper.ShopMapper; @Repository
public class ShopDao {
@Autowired
private ShopMapper mapper; /**
* 获取shop
*/
public Shop getShop(int id) {
return mapper.getShop(id);
}
}

说明:只是去掉了设置数据源key的那一句代码

2、DataSourceAspect

package com.xxx.firstboot.common.datasource;

import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.stereotype.Component; import com.xxx.firstboot.dao.ShopDao; @Aspect
@Component
public class DataSourceAspect { /**
* 使用空方法定义切点表达式
*/
@Pointcut("execution(* com.xxx.firstboot.dao.*.*(..))")
public void declareJointPointExpression() {
} /**
* 使用定义切点表达式的方法进行切点表达式的引入
*/
@Before("declareJointPointExpression()")
public void setDataSourceKey(JoinPoint point) {
// 连接点所属的类实例是ShopDao
if (point.getTarget() instanceof ShopDao) {
DatabaseContextHolder.setDatabaseType(DatabaseType.mytestdb2);
} else {// 连接点所属的类实例是UserDao(当然,这一步也可以不写,因为defaultTargertDataSource就是该类所用的mytestdb)
DatabaseContextHolder.setDatabaseType(DatabaseType.mytestdb);
}
} }

注意:该切点表达式也可以用在其他切面类中,引入的时候使用"全类名.切点方法名()",例:@Before("com.xxx.firstboot.common.datasource.DataSourceAspect.declareJointPointExpression()")