问题场景:使用aop切面方法执行一些业务,过程中获取自定义注解,并对自定义注解中的注入字段进行其他操作
执行的方法是有注解的,但是通过Annonation an = method.getAnnonation(UserStatus.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