AOP(Aspect Orient Programming),一般稱為面向切面編程,作為面向?qū)ο蟮囊环N補(bǔ)充,用于處理系統(tǒng)中分布于各個模塊的橫切關(guān)注點(diǎn),比如事務(wù)管理、日志、緩存等等。AOP實(shí)現(xiàn)的關(guān)鍵在于AOP框架自動創(chuàng)建的AOP代理,AOP代理主要分為靜態(tài)代理和動態(tài)代理,靜態(tài)代理的代表為AspectJ;而動態(tài)代理則以Spring AOP為代表。靜態(tài)代理是編譯期實(shí)現(xiàn),動態(tài)代理是運(yùn)行期實(shí)現(xiàn),可想而知前者擁有更好的性能。 本文主要介紹Spring AOP的兩種代理實(shí)現(xiàn)機(jī)制,JDK動態(tài)代理和CGLIB動態(tài)代理。 靜態(tài)代理是編譯階段生成AOP代理類,也就是說生成的字節(jié)碼就織入了增強(qiáng)后的AOP對象;動態(tài)代理則不會修改字節(jié)碼,而是在內(nèi)存中臨時生成一個AOP對象,這個AOP對象包含了目標(biāo)對象的全部方法,并且在特定的切點(diǎn)做了增強(qiáng)處理,并回調(diào)原對象的方法。 Spring AOP中的動態(tài)代理主要有兩種方式,JDK動態(tài)代理和CGLIB動態(tài)代理。JDK動態(tài)代理通過反射來接收被代理的類,并且要求被代理的類必須實(shí)現(xiàn)一個接口。JDK動態(tài)代理的核心是InvocationHandler接口和Proxy類。 如果目標(biāo)類沒有實(shí)現(xiàn)接口,那么Spring AOP會選擇使用CGLIB來動態(tài)代理目標(biāo)類。CGLIB(Code Generation Library),是一個代碼生成的類庫,可以在運(yùn)行時動態(tài)的生成某個類的子類,注意,CGLIB是通過繼承的方式做的動態(tài)代理,因此如果某個類被標(biāo)記為final,那么它是無法使用CGLIB做動態(tài)代理的,諸如private的方法也是不可以作為切面的。 我們分別通過實(shí)例來研究AOP的具體實(shí)現(xiàn)。 直接使用Spring AOP首先定義需要切入的接口和實(shí)現(xiàn)。為了簡單起見,定義一個Speakable接口和一個具體的實(shí)現(xiàn)類,只有兩個方法sayHi()和sayBye()。 public interface Speakable { void sayHi(); void sayBye();}@Servicepublic class PersonSpring implements Speakable { @Override public void sayHi() { try { Thread.currentThread().sleep(30); } catch (Exception e) { throw new RuntimeException(e); } System.out.println('Hi!!'); } @Override public void sayBye() { try { Thread.currentThread().sleep(10); } catch (Exception e) { throw new RuntimeException(e); } System.out.println('Bye!!'); }} 接下來我們希望實(shí)現(xiàn)一個記錄sayHi()和sayBye()執(zhí)行時間的功能。 定義一個MethodMonitor類用來記錄Method執(zhí)行時間 public class MethodMonitor { private long start; private String method; public MethodMonitor(String method) { this.method = method; System.out.println('begin monitor..'); this.start = System.currentTimeMillis(); } public void log() { long elapsedTime = System.currentTimeMillis() - start; System.out.println('end monitor..'); System.out.println('Method: ' + method + ', execution time: ' + elapsedTime + ' milliseconds.'); }} 光有這個類還是不夠的,希望有個靜態(tài)方法用起來更順手,像這樣 MonitorSession.begin();doWork();MonitorSession.end(); 說干就干,定義一個MonitorSession public class MonitorSession { private static ThreadLocal<MethodMonitor> monitorThreadLocal = new ThreadLocal<>(); public static void begin(String method) { MethodMonitor logger = new MethodMonitor(method); monitorThreadLocal.set(logger); } public static void end() { MethodMonitor logger = monitorThreadLocal.get(); logger.log(); }} 萬事具備,接下來只需要我們做好切面的編碼, @Aspect@Componentpublic class MonitorAdvice { @Pointcut('execution (* com.deanwangpro.aop.service.Speakable.*(..))') public void pointcut() { } @Around('pointcut()') public void around(ProceedingJoinPoint pjp) throws Throwable { MonitorSession.begin(pjp.getSignature().getName()); pjp.proceed(); MonitorSession.end(); }} 如何使用?我用了spring boot,寫一個啟動函數(shù)吧。 @SpringBootApplicationpublic class Application { @Autowired private Speakable personSpring; public static void main(String[] args) { SpringApplication.run(Application.class, args); } @Bean public CommandLineRunner commandLineRunner(ApplicationContext ctx) { return args -> { // spring aop System.out.println('******** spring aop ******** '); personSpring.sayHi(); personSpring.sayBye(); System.exit(0); }; }} 運(yùn)行后輸出:
JDK動態(tài)代理剛剛的例子其實(shí)內(nèi)部實(shí)現(xiàn)機(jī)制就是JDK動態(tài)代理,因?yàn)镻erson實(shí)現(xiàn)了一個接口。 為了不和第一個例子沖突,我們再定義一個Person來實(shí)現(xiàn)Speakable, 這個實(shí)現(xiàn)是不帶Spring Annotation的,所以他不會被Spring托管。 public class PersonImpl implements Speakable { @Override public void sayHi() { try { Thread.currentThread().sleep(30); } catch (Exception e) { throw new RuntimeException(e); } System.out.println('Hi!!'); } @Override public void sayBye() { try { Thread.currentThread().sleep(10); } catch (Exception e) { throw new RuntimeException(e); } System.out.println('Bye!!'); }} 重頭戲來了,我們需要利用InvocationHandler實(shí)現(xiàn)一個代理,讓它去包含Person這個對象。那么再運(yùn)行期實(shí)際上是執(zhí)行這個代理的方法,然后代理再去執(zhí)行真正的方法。所以我們得以在執(zhí)行真正方法的前后做一些手腳。JDK動態(tài)代理是利用反射實(shí)現(xiàn),直接看代碼。 public class DynamicProxy implements InvocationHandler { private Object target; public DynamicProxy(Object object) { this.target = object; } @Override public Object invoke(Object arg0, Method arg1, Object[] arg2) throws Throwable { MonitorSession.begin(arg1.getName()); Object obj = arg1.invoke(target, arg2); MonitorSession.end(); return obj; } @SuppressWarnings('unchecked') public <T> T getProxy() { return (T) Proxy.newProxyInstance( target.getClass().getClassLoader(), target.getClass().getInterfaces(), this ); }} 通過getProxy可以得到這個代理對象,invoke就是具體的執(zhí)行方法,可以看到我們在執(zhí)行每個真正的方法前后都加了Monitor。 我實(shí)現(xiàn)了一個工廠類來獲取Person代理對象 public class PersonProxyFactory { public static Speakable newJdkProxy() { // 代理PersonImpl DynamicProxy dynamicProxy = new DynamicProxy(new PersonImpl()); Speakable proxy = dynamicProxy.getProxy(); return proxy; }} 具體使用 // jdk dynamic proxySystem.out.println('******** jdk dynamic proxy ******** ');Speakable jdkProxy = PersonProxyFactory.newJdkProxy();jdkProxy.sayHi();jdkProxy.sayBye(); 輸出結(jié)果: ******** jdk dynamic proxy ******** begin monitor..Hi!!end monitor..Method: sayHi, execution time: 32 milliseconds.begin monitor..Bye!!end monitor..Method: sayBye, execution time: 22 milliseconds. CGLib動態(tài)代理我們再新建一個Person來,這次不實(shí)現(xiàn)任何接口。 public class Person { public void sayHi() { try { Thread.currentThread().sleep(30); } catch (Exception e) { throw new RuntimeException(e); } System.out.println('Hi!!'); } public void sayBye() { try { Thread.currentThread().sleep(10); } catch (Exception e) { throw new RuntimeException(e); } System.out.println('Bye!!'); }} 如果Spring識別到所代理的類沒有實(shí)現(xiàn)Interface,那么就會使用CGLib來創(chuàng)建動態(tài)代理,原理實(shí)際上成為所代理類的子類。 public class CGLibProxy implements MethodInterceptor { private static CGLibProxy instance = new CGLibProxy(); private CGLibProxy() { } public static CGLibProxy getInstance() { return instance; } private Enhancer enhancer = new Enhancer(); @SuppressWarnings('unchecked') public <T> T getProxy(Class<T> clazz) { enhancer.setSuperclass(clazz); enhancer.setCallback(this); return (T) enhancer.create(); } @Override public Object intercept(Object arg0, Method arg1, Object[] arg2, MethodProxy arg3) throws Throwable { MonitorSession.begin(arg1.getName()); Object obj = arg3.invokeSuper(arg0, arg2); MonitorSession.end(); return obj; }} 類似的通過getProxy可以得到這個代理對象,intercept就是具體的執(zhí)行方法,可以看到我們在執(zhí)行每個真正的方法前后都加了Monitor。 在工廠類中增加獲得Person代理類的方法, public static Person newCglibProxy() { CGLibProxy cglibProxy = CGLibProxy.getInstance(); Person proxy = cglibProxy.getProxy(Person.class); return proxy;} 具體使用 // cglib dynamic proxySystem.out.println('******** cglib proxy ******** ');Person cglibProxy = PersonProxyFactory.newCglibProxy();cglibProxy.sayHi();cglibProxy.sayBye(); 輸出結(jié)果:
小結(jié)對比JDK動態(tài)代理和CGLib代理,在實(shí)際使用中發(fā)現(xiàn)CGLib在創(chuàng)建代理對象時所花費(fèi)的時間卻比JDK動態(tài)代理要長,實(shí)測數(shù)據(jù) Method: newJdkProxy, execution time: 5 milliseconds.Method: newCglibProxy, execution time: 18 milliseconds. 所以CGLib更適合代理不需要頻繁實(shí)例化的類。 在具體方法執(zhí)行效率方面,理應(yīng)是不通過反射的CGlib更快一些,然后測試結(jié)果并非如此,還需要高手指教。
|
|