因Spring AOP导致@Autowired依赖注入失败的解决方法
发现问题:
之前用springAOP做了个操作日志记录,这次在往其他类上使用的时候,service一直注入失败,找了网上好多内容,发现大家都有类似的情况出现,但是又和自己的情况不太符合。后来总结自己的情况发现:方法为private修饰的,在AOP适配的时候会导致service注入失败,并且同一个service在其他的public方法中就没有这种情况,十分诡异。
解决过程:
结合查阅的资料进行了分析:在org.springframework.aop.support.AopUtils中:
publicstaticbooleancanApply(Pointcutpc,ClasstargetClass,booleanhasIntroductions){
if(!pc.getClassFilter().matches(targetClass)){
returnfalse;
}
MethodMatchermethodMatcher=pc.getMethodMatcher();
IntroductionAwareMethodMatcherintroductionAwareMethodMatcher=null;
if(methodMatcherinstanceofIntroductionAwareMethodMatcher){
introductionAwareMethodMatcher=(IntroductionAwareMethodMatcher)methodMatcher;
}
Setclasses=newHashSet(ClassUtils.getAllInterfacesForClassAsSet(targetClass));
classes.add(targetClass);
for(Iteratorit=classes.iterator();it.hasNext();){
Classclazz=(Class)it.next();
Method[]methods=clazz.getMethods();
for(intj=0;j
此处Method[]methods=clazz.getMethods();只能拿到public方法。
execution(**(..))可以匹配public/protected的,因为public的有匹配的了,目标类就代理了,,,再进行切入点匹配时也是能匹配的,而且cglib方式能拿到包级别/protected方法,而且包级别/protected方法可以直接通过反射调用。
private修饰符的切入点无法匹配Method[]methods=clazz.getMethods();这里的任何一个,因此无法代理的。所以可能因为private方法无法被代理,导致@Autowired不能被注入。
修正办法:
1、将方法修饰符改为public;
2、使用AspectJ来进行注入。
总结
以上就是这篇文章的全部内容了,希望本文的内容对大家的学习或者工作能带来一定的帮助,如果有疑问大家可以留言交流,谢谢大家对毛票票的支持。
热门推荐
1 训练狗狗基础
2 怎么训练狗狗笑
3 怎么训练狗狗卧下
4 上海狗狗训练基地
5 训练狗狗排便
6 狗狗基础训练
8 如何训练狗狗装死
9 狗狗站姿训练
10 狗狗训练用品
11 训练狗狗吧
12 狗狗要怎么训练
13 怎么训练狗狗玩球
14 训练狗狗唤回
15 狗狗训练躺下
16 狗狗训练指令
17 狗狗的训练技巧
18 狗狗不好训练