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

作者:ngulc 时间:2022-10-24 19:44:11 

发现问题:

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

来源:http://www.cnblogs.com/lcngu/p/6246950.html

标签:springaop,@autowired,依赖注入失败
0
投稿

猜你喜欢

  • Java Swing实现窗体添加背景图片的2种方法详解

    2021-10-26 19:01:18
  • Java 六类运算符详解

    2023-08-27 20:37:37
  • 详解IDEA中SpringBoot整合Servlet三大组件的过程

    2023-05-06 15:23:13
  • Spring框架构造注入type属性实例详解

    2021-10-04 19:45:19
  • Java 归并排序算法、堆排序算法实例详解

    2023-11-25 09:43:25
  • springboot之如何获取项目目录路径

    2022-08-09 21:44:17
  • Flutter Widgets之标签类控件Chip详解

    2023-06-26 14:22:35
  • C#与C++ dll之间传递字符串string wchar_t* char* IntPtr问题

    2022-09-16 09:34:53
  • Jsoup获取全国地区数据属性值(省市县镇村)

    2023-12-08 01:27:25
  • Android API开发之SMS短信服务处理和获取联系人的方法

    2021-10-23 03:22:15
  • 详解利用spring-security解决CSRF问题

    2023-07-31 14:31:19
  • java结束进程的实例代码

    2023-11-10 14:18:38
  • Spring容器中添加bean的5种方式

    2023-03-23 03:03:15
  • C#中利用Lotus notes公共邮箱发送邮件的方法

    2023-10-02 03:00:12
  • C# 获取指定QQ头像绘制圆形头像框GDI(Graphics)的方法

    2023-03-26 14:44:41
  • 通过spring注解开发,简单测试单例和多例区别

    2023-11-06 09:18:31
  • java实现静默加载Class示例代码

    2023-12-18 22:06:52
  • Android高级组件Gallery画廊视图使用方法详解

    2023-07-03 14:10:48
  • 解决Maven中关于依赖导入不进的问题

    2023-09-05 23:13:08
  • IDEA2020.1常用配置说明

    2023-01-09 02:11:50
  • asp之家 软件编程 m.aspxhome.com