1. 真的假的?查閱文檔
剛看到這個說法的時候,我是保持懷疑態度的。
大家都知道 Spring5 之前的版本 AOP 在默認情況下是使用 JDK 動態代理的,那是不是 Spring5 版本真的做了修改呢?於是我打開 Spring Framework 5.x 文檔,再次確認了一下:
文檔地址:https://docs.spring.io/spring/docs/5.2.0.RELEASE/spring-framework-reference/core.html#aop
簡單翻譯一下。Spring AOP 默認使用 JDK 動態代理,如果對象沒有實現接口,則使用 CGLIB 代理。當然,也可以強制使用 CGLIB 代理。也就是沒有改變
2 .SpringBoot 2.x 代碼示例
public interface ClassInterE{ public void funA(); } @Component public class ClassSonE implements ClassInterE{ @Transactional public void funA(){} public void funB(){} }
ClassSonE實現了ClassInterE接口,同時使用@Transactional對ClassSonE#funA
方法進行前置增強攔截。
從運行結果來看,這里的確使用了 CGLIB 代理而不是 JDK 動態代理。
難道真的是文檔寫錯了?!
@EnableAspectJAutoProxy 源碼注釋
在 Spring Framework 中,是使用@EnableAspectJAutoProxy
注解來開啟 Spring AOP 相關功能的。Spring Framework 5.2.0.RELEASE 版本@EnableAspectJAutoProxy
注解源碼如下:
通過源碼注釋我們可以了解到:在 Spring Framework 5.2.0.RELEASE 版本中,proxyTargetClass
的默認取值依舊是false
,默認還是使用 JDK 動態代理。難道文檔和源碼注釋都寫錯了?!
Spring Framework 5.x 整理一下思路
- 有人說 Spring5 開始 AOP 默認使用 CGLIB 了
- Spring Framework 5.x 文檔和
@EnableAspectJAutoProxy
源碼注釋都說了默認是使用 JDK 動態代理 - 程序運行結果說明,即使繼承了接口,設置
proxyTargetClass
為false
,程序依舊使用 CGLIB 代理
3 . 示例程序是使用 SpringBoot 來運行的,那如果不用 SpringBoot,只用 Spring Framework 會怎么樣呢?
運行結果表明:在 Spring Framework 5.x 版本中,如果類實現了接口,AOP 默認還是使用 JDK 動態代理。
再探 SpringBoot 2.x
- Spring5 AOP 默認依舊使用 JDK 動態代理,官方文檔和源碼注釋沒有錯。
- SpringBoot 2.x 版本中,AOP 默認使用 cglib,且無法通過
proxyTargetClass
進行修改。 - 那是不是 SpringBoot 2.x 版本做了一些改動呢?
源碼分析
源碼分析,找對入口很重要。那這次的入口在哪里呢?
@SpringBootApplication
是一個組合注解,該注解中使用@EnableAutoConfiguration
實現了大量的自動裝配。
EnableAutoConfiguration
也是一個組合注解,在該注解上被標志了@Import
。關於@Import
注解的詳細用法,可以參看筆者之前的文章:https://mp.weixin.qq.com/s/7arh4sVH1mlHE0GVVbZ84Q
@Target(ElementType.TYPE) @Retention(RetentionPolicy.RUNTIME) @Documented @Inherited @AutoConfigurationPackage @Import(AutoConfigurationImportSelector.class) public @interface EnableAutoConfiguration {}
在 Spring Framework 4.x 版本中,這是一個空接口,它僅僅是繼承了ImportSelector
接口而已。而在 5.x 版本中拓展了DeferredImportSelector
接口,增加了一個getImportGroup
方法:
在這個方法中返回了AutoConfigurationGroup
類。這是AutoConfigurationImportSelector
中的一個內部類,他實現了DeferredImportSelector.Group
接口。
在 SpringBoot 2.x 版本中,就是通過AutoConfigurationImportSelector.AutoConfigurationGroup#process
方法來導入自動配置類的。
通過斷點調試可以看到,和 AOP 相關的自動配置是通過org.springframework.boot.autoconfigure.aop.AopAutoConfiguration
來進行配置的。
真相大白
看到這里,可以說是真相大白了。在 SpringBoot2.x 版本中,通過AopAutoConfiguration
來自動裝配 AOP。
默認情況下,是肯定沒有spring.aop.proxy-target-class
這個配置項的。而此時,在 SpringBoot 2.x 版本中會默認使用 Cglib 來實現。
5. SpringBoot 2.x 中如何修改 AOP 實現
通過源碼我們也就可以知道,在 SpringBoot 2.x 中如果需要修改 AOP 的實現,需要通過spring.aop.proxy-target-class
這個配置項來修改。
#在application.properties文件中通過spring.aop.proxy-target-class來配置
spring.aop.proxy-target-class=false

總結
- Spring 5.x 中 AOP 默認依舊使用 JDK 動態代理。
- SpringBoot 2.x 開始,為了解決使用 JDK 動態代理可能導致的類型轉化異常而默認使用 CGLIB。
- 在 SpringBoot 2.x 中,如果需要默認使用 JDK 動態代理可以通過配置項
spring.aop.proxy-target-class=false
來進行修改,proxyTargetClass
配置已無效。