AOP获取方法注解实现动态切换数据源

AOP获取方法注解实现动态切换数据源

(其中@Order(1)作用:

Spring中的事务是通过aop来实现的,当我们自己写aop拦截的时候,会遇到跟spring的事务aop执行的先后顺序问题,比如说动态切换数据源的问题,如果事务在前,数据源切换在后,会导致数据源切换失效,所以就用到了Order(排序)这个关键字.)

@Order(1)
@Aspect
@Repository
public class DataSourceAspect {

    @Pointcut("execution(* com.xxx.service.impl.*.*(..))")
    private void anyMethod() {}

    @AfterReturning(value = "anyMethod()", returning = "result")
    public void afterReturning(JoinPoint joinPoint,Object result){
        DataSourceHolder.clearDataSourceType();
    }

    @Before(value="anyMethod()")
    public void before(JoinPoint joinPoint){
     //通过切点对象获取当前切点所在的方法对象 MethodSignature methodSignature
= (MethodSignature) joinPoint.getSignature(); Method method = methodSignature.getMethod(); //如果方法体上使用了DataSource注解 if (method.isAnnotationPresent(DataSource.class)) { //获取该方法上的注解名 DataSource datasource = method.getAnnotation(DataSource.class); //将方法体上的注解的值赋予给DataSourceHolder数据源持有类 DataSourceHolder.setDataSourceType(datasource.value()); } } }

猜你喜欢

转载自www.cnblogs.com/libin6505/p/11227267.html