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

今天想使用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

感谢。

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值