用springAOP做操作日志记录,发现:方法为private修饰的,在AOP适配的时候会导致service注入失败,但是同一个service其他的public方法正常
public static boolean canApply(Pointcut pc, Class targetClass, boolean hasIntroductions) { if (!pc.getClassFilter().matches(targetClass)) { return false; } MethodMatcher methodMatcher = pc.getMethodMatcher(); IntroductionAwareMethodMatcher introductionAwareMethodMatcher = null; if (methodMatcher instanceof IntroductionAwareMethodMatcher) { introductionAwareMethodMatcher = (IntroductionAwareMethodMatcher) methodMatcher; } Set classes = new HashSet(ClassUtils.getAllInterfacesForClassAsSet(targetClass)); classes.add(targetClass); for (Iterator it = classes.iterator(); it.hasNext();) { Class clazz = (Class) it.next(); Method[] methods = clazz.getMethods(); for (int j = 0; j < methods.length; j++) { if ((introductionAwareMethodMatcher != null && introductionAwareMethodMatcher.matches(methods[j], targetClass, hasIntroductions)) || methodMatcher.matches(methods[j], targetClass)) { return true; } } } return false; }
1. 这里的Method[] methods = clazz.getMethods();只能获得public方法。
2. execution(* *(…)) 可以匹配public/protected的,因为public的有匹配的了,目标类就代理了,再进行切入点匹配时也是能匹配的,而且cglib方式能拿到包级别/protected方法,而且包级别/protected方法可以直接通过反射调用。
3. private 修饰符的切入点 无法匹配 Method[] methods = clazz.getMethods(); 这里的任何一个,因此无法代理的。 所以可能因为private方法无法被代理,导致@Autowired不能被注入。
解决:
方法修饰符为public;
使用AspectJ注入。