网创优客建站品牌官网
为成都网站建设公司企业提供高品质网站建设
热线:028-86922220
成都专业网站建设公司

定制建站费用3500元

符合中小企业对网站设计、功能常规化式的企业展示型网站建设

成都品牌网站建设

品牌网站建设费用6000元

本套餐主要针对企业品牌型网站、中高端设计、前端互动体验...

成都商城网站建设

商城网站建设费用8000元

商城网站建设因基本功能的需求不同费用上面也有很大的差别...

成都微信网站建设

手机微信网站建站3000元

手机微信网站开发、微信官网、微信商城网站...

建站知识

当前位置:首页 > 建站知识

使用SpringAOP时出现@Autowired依赖无法注入如何解决

这篇文章给大家介绍使用Spring AOP时出现@Autowired依赖无法注入如何解决,内容非常详细,感兴趣的小伙伴们可以参考借鉴,希望对大家能有所帮助。

我们提供的服务有:成都做网站、网站制作、微信公众号开发、网站优化、网站认证、尚义ssl等。为成百上千企事业单位解决了网站和推广的问题。提供周到的售前咨询和贴心的售后服务,是有科学管理、有技术的尚义网站制作公司

发现问题:

之前用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来进行注入。

关于使用Spring AOP时出现@Autowired依赖无法注入如何解决就分享到这里了,希望以上内容可以对大家有一定的帮助,可以学到更多知识。如果觉得文章不错,可以把它分享出去让更多的人看到。


新闻名称:使用SpringAOP时出现@Autowired依赖无法注入如何解决
网站地址:http://bjjierui.cn/article/geiehs.html

其他资讯