您的位置:首页 > 编程语言 > Java开发

【第九章】 springboot + mybatis + 多数据源 (AOP实现)

2017-07-13 13:37 701 查看

在第八章 springboot + mybatis + 多数据源代码的基础上,做两点修改

1、ShopDao

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);
}
}

}
View Code

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

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: