AOP日記
Aop中叫代理類為advice,可以有多個(gè)連接起來(lái),一個(gè)事件鏈
實(shí)現(xiàn)AOP,還需要涉及到JAVA的反射,通過(guò)反射,獲取method對(duì)象,并執(zhí)行方法,AOP規(guī)范包里有個(gè)接口
public interface MethodInterceptor extends Interceptor {
*Implement this method to perform extra treatments before and
* after the invocation. Polite implementations would certainly
* like to invoke {@link Joinpoint#proceed()}.
*
* @param invocation the method invocation joinpoint
* @return the result of the call to {@link
* Joinpoint#proceed()}, might be intercepted by the
* interceptor.
*
* @throws Throwable if the interceptors or the
* target-object throws an exception.
Object invoke(MethodInvocation invocation) throws Throwable;
}
通過(guò) MethodInvocation的 getMethod()獲得方法對(duì)象,并執(zhí)行
這樣,如果你一個(gè)類中有很多方法,就可以通過(guò)這么一個(gè)
AOP中生成代理類有3種方式,
1.靜態(tài)編譯時(shí)期,源代碼生成,為每個(gè)符合條件的類生成一個(gè)代理類
2.靜態(tài)字節(jié)碼增強(qiáng)通過(guò)ASM/CGLIB分析字節(jié)碼,生成代理類
3.動(dòng)態(tài)字節(jié)碼增強(qiáng),spring aop就是這樣,ASM/CGLIB或者JDK的動(dòng)態(tài)代理
AOP的原理可以理解為代理模式+放射+自動(dòng)字節(jié)碼生成
Spring中動(dòng)態(tài)代理有2種方式,一種是通過(guò)CGLIB,一種是JDK。
什么時(shí)候采用JDK什么時(shí)候采用CGLIB動(dòng)態(tài)生成,主要取決于你又沒(méi)實(shí)現(xiàn)接口,JDK動(dòng)態(tài)代理需要目標(biāo)類實(shí)現(xiàn)某接口,而CGLIB則是生成目標(biāo)類的子類
public AopProxy createAopProxy(AdvisedSupport config) throws AopConfigException {
if (config.isOptimize() || config.isProxyTargetClass() || hasNoUserSuppliedProxyInterfaces(config)) {
Class targetClass = config.getTargetClass();
if (targetClass == null) {
throw new AopConfigException("TargetSource cannot determine target class: " +
"Either an interface or a target is required for proxy creation.");
}
if (targetClass.isInterface()) {
return new JdkDynamicAopProxy(config);
}
if (!cglibAvailable) {
throw new AopConfigException(
"Cannot proxy target class because CGLIB2 is not available. " +
"Add CGLIB to the class path or specify proxy interfaces.");
}
return CglibProxyFactory.createCglibProxy(config);
}
else {
return new JdkDynamicAopProxy(config);
}
}
這個(gè)是DefaultAopProxyFactory里創(chuàng)建代理類的方法
posted on 2010-10-24 23:48 羔羊 閱讀(321) 評(píng)論(0) 編輯 收藏 所屬分類: aop