解决AOP中代理获取不到Annotation的问题

今天想使用aop写一个缓存同步的注解遇到了一个问题

我用MethodSignature.getMethod();方法得不到目标对象的注解

  1. @After("@annotation(com.art.annotation.DeleteRedisCache)")
  2. public void deleteCacheById(JoinPoint joinPoint) {
  3. MethodSignature methodSignature = (MethodSignature) joinPoint.getSignature();
  4. Method method = methodSignature.getMethod();
  5. DeleteRedisCache cache = method.getAnnotation(DeleteRedisCache.class);
  6. //得到的cache是null
  7. System.out.println(cache.Cachekey());
  8. }

在网上找了很多,原因是spring aop使用cglib生成的代理是不会加上父类的方法上的注解的。

我们看一下对比

错误写法(获取到的是代理对象)

  1. @After("@annotation(com.art.annotation.DeleteRedisCache)")
  2. public void deleteCacheById(JoinPoint joinPoint) {
  3. MethodSignature methodSignature = (MethodSignature) joinPoint.getSignature();
  4. Method method = methodSignature.getMethod();
  5. //cache是代理对象,methodSignature里并没有 joinPoint.getSignature()的注解
  6. DeleteRedisCache cache = method.getAnnotation(DeleteRedisCache.class);
  7. System.out.println(cache.Cachekey());
  8. }

正确写法(获取到的是目标对象)

  1. @After("@annotation(com.art.annotation.DeleteRedisCache)")
  2. public void deleteCacheById(JoinPoint joinPoint) {
  3. Method realMethod = point.getTarget().getClass().getDeclaredMethod(signature.getName(),
  4. method.getParameterTypes());
  5. //此处realMethod是目标对象(原始的)的方法
  6. Annotation an = method.getAnnotation(UserChangeLog.class);
  7. //此处 an 不为null
  8. }

参考:https://blog.csdn.net/frightingforambition/article/details/78842306