javascript
Spring5参考指南:AOP代理
文章目錄
- AOP代理
- AOP Proxies原理
AOP代理
通常來說Spring AOP有兩種代理方式,一種默認的JDK代理,只能代理接口,一種是CGLIB代理,可以代理具體的類對象。
SpringAOP默認為對AOP代理使用標準的JDK動態代理。如果業務對象不實現接口,則使用CGLIB。
如果使用CGLIB,要注意對于CGLIB,不能advice final方法,因為它們不能在運行時生成的子類中被重寫。
由于Spring的AOP框架基于代理的特性,根據定義,目標對象內的方法調用不會被攔截。對于JDK代理,只能截獲對代理的公共接口方法調用。使用cglib,可以截獲代理上的公共和受保護的方法調用(如果需要,甚至可以截獲包可見的方法)。
如果需要攔截在目標類內的方法調用甚至構造函數,那么考慮使用Spring驅動的native AspectJ weaving,而不是Spring的基于代理的AOP框架。
要強制使用CGLIB代理,請將aop:config元素的proxy target class屬性的值設置為true,如下所示:
<aop:config proxy-target-class="true"><!-- other beans defined here... --> </aop:config>要在使用@Aspectj auto proxy支持時強制cglib代理,請將aop:aspectj-autoproxy元素的proxy-target-class屬性設置為true,如下所示:
<aop:aspectj-autoproxy proxy-target-class="true"/>AOP Proxies原理
SpringAOP是基于代理的,那什么是代理呢?
首先我們考慮一個最簡單的POJO對象:
public class SimplePojo implements Pojo {public void foo() {// this next method invocation is a direct call on the 'this' referencethis.bar();}public void bar() {// some logic...} }如果直接調用該對象的方法,則運行原理如下所示:
調用方法如下:
public class Main {public static void main(String[] args) {Pojo pojo = new SimplePojo();// this is a direct method call on the 'pojo' referencepojo.foo();} }如果是調用代理,則運行原理如下:
調用方法如下:
public class Main {public static void main(String[] args) {ProxyFactory factory = new ProxyFactory(new SimplePojo());factory.addInterface(Pojo.class);factory.addAdvice(new RetryAdvice());Pojo pojo = (Pojo) factory.getProxy();// this is a method call on the proxy!pojo.foo();} }本文的例子請參考aop-proxy
更多精彩內容且看:
- 區塊鏈從入門到放棄系列教程-涵蓋密碼學,超級賬本,以太坊,Libra,比特幣等持續更新
- Spring Boot 2.X系列教程:七天從無到有掌握Spring Boot-持續更新
- Spring 5.X系列教程:滿足你對Spring5的一切想象-持續更新
- java程序員從小工到專家成神之路(2020版)-持續更新中,附詳細文章教程
更多教程請參考 flydean的博客
總結
以上是生活随笔為你收集整理的Spring5参考指南:AOP代理的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Spring5参考指南:基于Schema
- 下一篇: Spring5参考指南:AspectJ高