用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;
    }
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章