首页 > 技术文章 > SpringAOP和AspectJ

lanqi 2018-05-25 13:48 原文

SpringAOP和AspectJ的关系

问题:之前对 SpringAOP和AspectJ的关系感到疑惑,因为曾经在书上看过SpringAOP集成了AspectJ,那么SpringAOP是直接使用了AspectJ吗?那么为什么又说SpringAOP是使用的JDK动态代理和Cglib?书上关于这一部分就没有细说了。于是查阅了官方文档后,得到了答案。

先贴一段官方的解释

@AspectJ refers to a style of declaring aspects as regular Java classes annotated with annotations. The @AspectJ style was introduced by the AspectJ project as part of the AspectJ 5 release. Spring interprets the same annotations as AspectJ 5, using a library supplied by AspectJ for pointcut parsing and matching. The AOP runtime is still pure Spring AOP though, and there is no dependency on the AspectJ compiler or weaver.

顺便翻译一下:当使用@AspectJ注解时,spring使用了 AspectJ库的注解并且使用 AspectJ库对切点表达式进行解析和匹配,但AOP运行时并不使用 AspectJ的编译器和织入,仍然是使用纯粹的springAOP实现。
从这一段可以看到Spring的确集成了AspectJ,但只是使用AspectJ库对切点表达式进行解析和匹配功能,代理部分仍然是使用的JDK动态代理和Cglib。这个解释为什么使用了@Transactional的方法再内部调用时,事务是不起作用的。因为springAop的代理是基于方法的,而内部调用方法并未被代理,被代理的是使用了@Transactional注解的方法。解决这个问题可以配置spring使用
AspectJ进行代理。

推荐阅读