- Spring Boot進階:原理、實戰與面試題分析
- 鄭天民
- 310字
- 2022-07-05 09:41:48
3.2.2 CGLIB動態代理
CGLIB是一個Java字節碼生成庫,提供了易用的API對Java字節碼進行創建和修改。我們現在嘗試用CGLIB來代理前面的RealAccount類,如代碼清單3-9所示。
代碼清單3-9 AccountCglibProxy類代碼
public class AccountCglibProxy implements MethodInterceptor { private Enhancer enhancer = new Enhancer(); public Object getProxy(Class<?> clazz) { enhancer.setSuperclass(clazz); enhancer.setCallback(this); return enhancer.create(); } public Object intercept(Object obj, Method method, Object[] args, MethodProxy proxy) throws Throwable { System.out.println("before"); Object object = proxy.invokeSuper(obj, args); System.out.println("after"); return object; } }
上述代碼中的Enhancer類是CGLIB中最常用的一個類,類似于前面介紹的JDK動態代理中的Proxy類。和Proxy只能代理接口不同,Enhancer既能夠代理接口,也能夠代理普通類,但不能攔截final類和方法。在這里,我們實現了MethodInterceptor中的intercept()方法以提供代理邏輯。
AccountCglibProxy類的使用方法也比較簡單,如代碼清單3-10所示。
代碼清單3-10 AccountCglibProxy類使用方法代碼
AccountCglibProxy proxy = new AccountCglibProxy(); RealAccount account = (RealAccount) proxy.getProxy(RealAccount.class); account.open();
作為對比,我們用表3-1展示了JDK動態代理和CGLIB動態代理之間的區別。
表3-1 JDK動態代理和CGLIB動態代理對比

推薦閱讀
- C++程序設計教程
- UML+OOPC嵌入式C語言開發精講
- 編寫高質量代碼:改善C程序代碼的125個建議
- 深入淺出Serverless:技術原理與應用實踐
- ASP.NET程序設計教程
- FPGA嵌入式項目開發實戰
- 深入解析Java編譯器:源碼剖析與實例詳解
- JavaWeb從入門到精通(視頻實戰版)
- JBoss AS 7 Development
- Building Web and Mobile ArcGIS Server Applications with JavaScript(Second Edition)
- 軟件開發中的決策:權衡與取舍
- Mastering R for Quantitative Finance
- Python網絡爬蟲從入門到實踐
- Learning Perforce SCM
- 青少年編程魔法課堂:Python圖形化創意編程