问题场景:使用aop切面方法执行一些业务,过程中查看执行的方法是否有一个自定义的注解,有的话做其他的操作
这里碰到了一个问题 ,执行的方法有注解,但是通过Annotation an = method.getAnnotation(UserChangeLog.class); 取值为null.
具体情况和此篇文章类似:示例
其实问题很简单,是代理对象和目标对象的问题,通过代理模式生成代理对象上的方法不会有注解,我们要取注解只能从目标对象中取。
错误写法:
Method method=((MethodSignature)point.getSignature()).getMethod();
//此处method获取的是代理对象(由代理模式生成的)的方法
Annotation an = method.getAnnotation(UserChangeLog.class);
//此处 an 为 null
正确写法:
Method realMethod = point.getTarget().getClass().getDeclaredMethod(signature.getName(),
method.getParameterTypes());
//此处realMethod是目标对象(原始的)的方法
Annotation an = method.getAnnotation(UserChangeLog.class);
//此处 an 不为null

本文探讨了在AOP编程中如何正确地从代理对象获取原始目标对象的注解信息。当通过代理对象获取不到注解时,文章提供了一种有效的方法来解决这一问题,并附带示例代码。
903





