SpringAop切面实现日志记录

  • 2019 年 11 月 29 日
  • 筆記

SpringAop切面实现日志记录 代码实现:https://www.cnblogs.com/wenjunwei/p/9639909.html

问题记录

1.signature.getMethod().getAnnotation()无法获取注解对象

原因:Spring在处理中,可能是因为我的项目有事务,serviceImpl的方法被代理后直接得不到了。换一个思路:先得到自己的父类,然后通过父类得到真实的自己 解决方法: https://www.cnblogs.com/wangshen31/p/9498731.html

 1 /**   2      * 这个方法帮忙拿出注解中的operation属性   3      * 因为有拦截serviceImpl的方法,而这些方法又加了事务管理,也就是这里也有aop,这些已经是代理类,用之前的写法获得的是代理类的方法,而这些   4      * 方法是特么不会把父类中的方法的注解加上去的!!!   5      * @param proceedingJoinPoint   6      */   7     private String getOperationOfTheAnnotation(ProceedingJoinPoint proceedingJoinPoint) throws Exception {   8   9         Signature signature =  proceedingJoinPoint.getSignature();//方法签名  10         Method method = ( (MethodSignature)signature ).getMethod();  11  12         //这个方法才是目标对象上有注解的方法  13         Method realMethod = proceedingJoinPoint.getTarget().getClass().getDeclaredMethod(signature.getName(), method.getParameterTypes());  14  15  16         AuthorizationNeed authorizationNeed = realMethod.getAnnotation(AuthorizationNeed.class);  17  18         return authorizationNeed.operation();  19  20  21     }

2.signature.getParameterNames() 获取不到值

原因:如果您的bean实现了接口,那么JDK代理将在spring之前创建,并且在这种代理中,MethodSignature.getParameterNames()为null。 如果您的bean没有实现接口,则会创建CGLIB代理,并在其中填充MethodSignature.getParameterNames()。 解决方案: http://www.it1352.com/990863.html 使用CGLIB代理,spring.aop.proxy-target-class: true (设置为true)

1 server:  2   port:8087  3 spring:  4   aop:  5     auto: true #启动aop配置  6     proxy-target-class: true