Spring AOP 本質(2)
Spring AOP架構的核心是創建在代理上的。
Spring AOP代理只支持一種鏈接點----方法調用。其功能是AOP規範的一個子集,但足夠用了。
Spring代理有兩種實現方式:JDK動態代理和CGLIB代理。CGLIB的代理性能要比JDK動態代理的性能好不少,不過開發人員不用須要關注這些,Spring自動會判斷使用何種代理,而且默認Spring會選擇使用CGLIB的代理,在此不作深刻討論。
Spring AOP代理是經過ProxyFactory類來獲取代理對象的。最簡單的過程是:
一、建立代理工廠:new一個ProxyFactory實例。
二、給代理工廠加入通知者:ProxyFactory.addAdvisor(),通知者構建方式不少。
三、將目標加入工廠:ProxyFactory.setTarget()設置要代理的對象。
四、獲取目標的代理實例:ProxyFactory.getProxy(),經過代理實例來執行被代理的也沒法方法。
在Spring AOP中,有兩種方法將一個通知加入到代理中去。一是直接使用addAdvice()方法,二是使用addAdvice()和Advisor(通知者)類。前者在ProxyFactory中會委派給addAdvisor(),加入的是DefaultPointcutAdvisor。
Spring支持五類通知,這些通知都實現了Advice接口:
org.springframework.aop.AfterReturningAdvice
org.springframework.aop.IntroductionInterceptor
org.springframework.aop.MethodBeforeAdvice
org.aopalliance.intercept.MethodInterceptor
org.springframework.aop.ThrowsAdvice
在實際中,只須要實現以上五個標準接口便可,另外這些接口都是AOP聯盟定義的標準接口。
下面經過實現MethodBeforeAdvice接口改寫「Spring AOP 本質(1) 」中的例子,其餘的不用改變,只須要將測試類實現MethodBeforeAdvice接口便可。
下面是改寫後的代碼:
import java.lang.reflect.Method;
import org.springframework.aop.MethodBeforeAdvice;
import org.springframework.aop.framework.ProxyFactory;
public
class SimpleBeforeAdvice
implements MethodBeforeAdvice {
public
static
void main(String[] args) {
//被代理對象
MessageWriter target =
new MessageWriter();
//代理工廠
ProxyFactory pf =
new ProxyFactory();
//給工廠添加通知(者),實際上ProxyFactory在後臺加入的是一個DefaultPointcutAdvisor
pf.addAdvice(
new SimpleBeforeAdvice());
//將目標加入代理工廠
pf.setTarget(target);
//從工廠獲取代理實例(產品)
MessageWriter proxy = (MessageWriter) pf.getProxy();
//從代理實例上調用業務方法
proxy.writeMessage();
}
public
void before(Method method, Object[] args, Object target)
throws Throwable {
System.out.println(
"Before method: " + method.getName());
}
}
運行結果:
- Using JDK 1.4 collections Before method: writeMessage World Process finished with exit code 0