1. 程式人生 > >SpringAOP導致@Autowired依賴注入失敗

SpringAOP導致@Autowired依賴注入失敗

 同事程式碼出現了一個詭異的問題,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來進行注入

原文連結:http://www.cnblogs.com/lcngu/p/6246950.html