欢迎来到代码驿站!

JAVA代码

当前位置:首页 > 软件编程 > JAVA代码

因Spring AOP导致@Autowired依赖注入失败的解决方法

时间:2022-03-11 08:51:50|栏目:JAVA代码|点击:

发现问题:

之前用springAOP做了个操作日志记录,这次在往其他类上使用的时候,service一直注入失败,找了网上好多内容,发现大家都有类似的情况出现,但是又和自己的情况不太符合。后来总结自己的情况发现:方法为private修饰的,在AOP适配的时候会导致service注入失败,并且同一个service在其他的public方法中就没有这种情况,十分诡异。

解决过程:

结合查阅的资料进行了分析:在org.springframework.aop.support.AopUtils中:

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; 
}

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

execution(* *(..)) 可以匹配public/protected的,因为public的有匹配的了,目标类就代理了,,,再进行切入点匹配时也是能匹配的,而且cglib方式能拿到包级别/protected方法,而且包级别/protected方法可以直接通过反射调用。 

private 修饰符的切入点 无法匹配 Method[] methods = clazz.getMethods(); 这里的任何一个,因此无法代理的。 所以可能因为private方法无法被代理,导致@Autowired不能被注入。

修正办法:

     1、将方法修饰符改为public;

     2、使用AspectJ来进行注入。

总结

上一篇:通过Java视角简单谈谈局部性原理

栏    目:JAVA代码

下一篇:java 如何使用org.w3c.dom操作XML文件

本文标题:因Spring AOP导致@Autowired依赖注入失败的解决方法

本文地址:http://www.codeinn.net/misctech/195877.html

推荐教程

广告投放 | 联系我们 | 版权申明

重要申明:本站所有的文章、图片、评论等,均由网友发表或上传并维护或收集自网络,属个人行为,与本站立场无关。

如果侵犯了您的权利,请与我们联系,我们将在24小时内进行处理、任何非本站因素导致的法律后果,本站均不负任何责任。

联系QQ:914707363 | 邮箱:codeinn#126.com(#换成@)

Copyright © 2020 代码驿站 版权所有