用aspectj拦截mybatis mapper的一种可行方案

实现的大致步骤
1、我们的mapper层接口统一实现一个接口比如Mapper接口
2、Aspect切面定义时候切点匹配用this或者target eg:
MethodInvocation methodInvocation = ExposeInvocationInterceptor.currentInvocation();这个句有值是因为Mapper代理的增强第一个就是ExposeInvocationInterceptor这个增强器会设置当前方法的MethodInvocation

@Aspect
@Order(value = Integer.MIN_VALUE + 3)
public class TestAspect3 {

    @Pointcut("this (org.springframework.jdbc.component.mapper.Mapper)")
    public void pointcut(){}


    @Around(value = "pointcut()")
    public Object around(ProceedingJoinPoint proceedingJoinPoint) throws Throwable {
        Object proceed = null;
        MethodInvocation methodInvocation = ExposeInvocationInterceptor.currentInvocation();
        if (methodInvocation != null){
            Annotation[] annotations = methodInvocation.getMethod().getAnnotations();
            if (annotations !=null){
                  for (Annotation annotation : annotations){
                      if (annotation.annotationType().equals(Test.class)){
                          Test test = (Test) annotation;
                          String times = test.times();
                          Object[] args = proceedingJoinPoint.getArgs();
                          System.out.println("TestAspect2 123");
                          System.out.println("TestAspect2 456");
                          for (int i = 0;i < Integer.parseInt(times);++i){
                              proceed = proceedingJoinPoint.proceed(proceedingJoinPoint.getArgs());
                          }
                          return proceed;
                      }
                  }
            }

        }
        proceed = proceedingJoinPoint.proceed(proceedingJoinPoint.getArgs());

        return proceed;
    }
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章