SpringAOP導致@Autowired依賴注入失敗


  之前用springAOP做了個操作日志記錄,這次在往其他類上使用的時候,service一直注入失敗,找了網上好多內容,發現大家都有類似的情況出現,但是又和自己的情況不太符合。后來總結自己的情況發現:方法為private修飾的,在AOP適配的時候會導致service注入失敗,並且同一個service在其他的public方法中就沒有這種情況,十分詭異。

  結合查閱的資料進行了分析:在org.springframework.aop.support.AopUtils中:

 1 public static boolean canApply(Pointcut pc, Class targetClass, boolean hasIntroductions) {  
 2     if (!pc.getClassFilter().matches(targetClass)) {  
 3         return false;  
 4     }  
 5   
 6     MethodMatcher methodMatcher = pc.getMethodMatcher();  
 7     IntroductionAwareMethodMatcher introductionAwareMethodMatcher = null;  
 8     if (methodMatcher instanceof IntroductionAwareMethodMatcher) {  
 9         introductionAwareMethodMatcher = (IntroductionAwareMethodMatcher) methodMatcher;  
10     }  
11   
12     Set classes = new HashSet(ClassUtils.getAllInterfacesForClassAsSet(targetClass));  
13     classes.add(targetClass);  
14     for (Iterator it = classes.iterator(); it.hasNext();) {  
15         Class clazz = (Class) it.next();  
16         Method[] methods = clazz.getMethods();  
17         for (int j = 0; j < methods.length; j++) {  
18             if ((introductionAwareMethodMatcher != null &&  
19                     introductionAwareMethodMatcher.matches(methods[j], targetClass, hasIntroductions)) ||  
20                     methodMatcher.matches(methods[j], targetClass)) {  
21                 return true;  
22             }  
23         }  
24     }  
25   
26     return false;  
27 }  

  此處Method[] methods = clazz.getMethods();只能拿到public方法。

  execution(* *(..)) 可以匹配public/protected的,因為public的有匹配的了,目標類就代理了,,,再進行切入點匹配時也是能匹配的,而且cglib方式能拿到包級別/protected方法,而且包級別/protected方法可以直接通過反射調用。  

  private 修飾符的切入點 無法匹配 Method[] methods = clazz.getMethods(); 這里的任何一個,因此無法代理的。 所以可能因為private方法無法被代理,導致@Autowired不能被注入。

  修正辦法:

1、將方法修飾符改為public;

2、使用AspectJ來進行注入。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM