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