今天想使用aop写一个缓存同步的注解遇到了一个问题
我用MethodSignature.getMethod();方法得不到目标对象的注解
@After("@annotation(com.art.annotation.DeleteRedisCache)")
public void deleteCacheById(JoinPoint joinPoint) {
MethodSignature methodSignature = (MethodSignature) joinPoint.getSignature();
Method method = methodSignature.getMethod();
DeleteRedisCache cache = method.getAnnotation(DeleteRedisCache.class);
//得到的cache是null
System.out.println(cache.Cachekey());
}
在网上找了很多,原因是spring aop使用cglib生成的代理是不会加上父类的方法上的注解的。
我们看一下对比
错误写法(获取到的是代理对象)
@After("@annotation(com.art.annotation.DeleteRedisCache)")
public void deleteCacheById(JoinPoint joinPoint) {
MethodSignature methodSignature = (MethodSignature) joinPoint.getSignature();
Method method = methodSignature.getMethod();
//cache是代理对象,methodSignature里并没有 joinPoint.getSignature()的注解
DeleteRedisCache cache = method.getAnnotation(DeleteRedisCache.class);
System.out.println(cache.Cachekey());
}
正确写法(获取到的是目标对象)
@After("@annotation(com.art.annotation.DeleteRedisCache)")
public void deleteCacheById(JoinPoint joinPoint) {
Method realMethod = point.getTarget().getClass().getDeclaredMethod(signature.getName(),
method.getParameterTypes());
//此处realMethod是目标对象(原始的)的方法
Annotation an = method.getAnnotation(UserChangeLog.class);
//此处 an 不为null
}
参考:https://blog.csdn.net/frightingforambition/article/details/78842306
感谢。