动态代理-JDK_proxycglib
生活随笔
收集整理的這篇文章主要介紹了
动态代理-JDK_proxycglib
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
2019獨角獸企業重金招聘Python工程師標準>>>
一、簡介
動態代理的實現方式較常用的方式有兩種,用jdk的proxy類實現,必須依賴接口。或者使用cglib的擴展包實現,因為是產生類的子類所以代理的類不能為final類。
二、示例
1、 其中UserServiceImpl 是 UserService的實現
( UserServiceImpl implements UserService )
2、使用JDK的Proxy進行代理
3、使用cglib進行代理實現
import?net.sf.cglib.proxy.Enhancer; ...public?class?CglibTestMain?{public?static?void?main(String[]?args)?{Enhancer?enhancer?=?new?Enhancer();enhancer.setSuperclass(UserServiceImpl.class);enhancer.setCallback(new?CglibMethodInterceptor(new?UserServiceImpl()));UserServiceImpl?userServiceProxy=?(UserServiceImpl)?enhancer.create();userServiceProxy.save();} } import?java.lang.reflect.Method;import?net.sf.cglib.proxy.MethodInterceptor; import?net.sf.cglib.proxy.MethodProxy;public?class?CglibMethodInterceptor?implements?MethodInterceptor?{private?Object?targetObj;public?CglibMethodInterceptor(Object?targetObj)?{this.targetObj?=?targetObj;}@Overridepublic?Object?intercept(Object?proxyObj,?Method?method,?Object[]?args,?MethodProxy?methodProxy)?throws?Throwable?{System.out.println("---begin---");Object?result?=?method.invoke(this.targetObj,?args);System.out.println("---end---");return?result;}}轉載于:https://my.oschina.net/sandant/blog/371895
總結
以上是生活随笔為你收集整理的动态代理-JDK_proxycglib的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: IOS UITableView性能优化
- 下一篇: SQL Server 2005 MD5