原文地址:http://my.oschina.net/huangyong/blog/161338
又是一個週末,剛給寶寶喂完牛奶,終於讓她睡着了。所以現在我才能騰出手來,坐在電腦面前給大家寫這篇文章。
今天我要和大家分享的是 AOP(Aspect-Oriented Programming)這個東西,名字與 OOP 僅差一個字母,其實它是對 OOP 編程方式的一種補充,並非是取而代之。翻譯過來就是“面向方面編程”,可我更傾向於翻譯爲“面向切面編程”。它聽起有些的神祕,爲什麼呢?當你看完這篇文章的時候,就會知道,我們做的很重要的工作就是去寫這個“切面” 。那麼什麼是“切面”呢?
沒錯!就是用一把刀來切一坨面。注意,相對於面而言,我們一定是橫着來切它,這簡稱爲“橫切”。可以把一段代碼想象成一坨面,同樣也可以用一把刀來橫切它,下面要做的就是如何去實現這把刀!
需要澄清的是,這個概念不是由 Rod Johnson(老羅)提出的。其實很早以前就有了,目前最知名最強大的 Java 開源項目就是 AspectJ 了,然而它的前身是 AspectWerkz(該項目已經在 2005 年停止更新),這纔是 AOP 的老祖宗。老羅(一個頭發禿得和我老爸有一拼的天才)寫了一個叫做 Spring 框架,從此一炮走紅,成爲了 Spring 之父。他在自己的 IOC 的基礎之上,又實現了一套 AOP 的框架,後來彷彿發現自己越來越走進深淵裏,在不能自拔的時候,有人建議他還是集成 AspectJ
吧,他在萬般無奈之下才接受了該建議。於是,我們現在用得最多的想必就是 Spring + AspectJ 這種 AOP 框架了。
那麼 AOP 到底是什麼?如何去使用它?本文將逐步帶您進入 AOP 的世界,讓您感受到前所未有的暢快!
不過在開始講解 AOP 之前,我想有必要回憶一下這段代碼:
1. 寫死代碼
先來一個接口:
1 |
public interface Greeting { |
3 |
void sayHello(String name); |
還有一個實現類:
01 |
public class GreetingImpl implements Greeting { |
04 |
public void sayHello(String name) { |
06 |
System.out.println( "Hello! " + name); |
10 |
private void before() { |
11 |
System.out.println( "Before" ); |
14 |
private void after() { |
15 |
System.out.println( "After" ); |
before() 與 after() 方法寫死在 sayHello() 方法體中了,這樣的代碼的味道非常不好。如果哪位仁兄大量寫了這樣的代碼,肯定要被你的架構師罵個夠嗆。
比如:我們要統計每個方法的執行時間,以對性能作出評估,那是不是要在每個方法的一頭一尾都做點手腳呢?
再比如:我們要寫一個 JDBC 程序,那是不是也要在方法的開頭去連接數據庫,方法的末尾去關閉數據庫連接呢?
這樣的代碼只會把程序員累死,把架構師氣死!
一定要想辦法對上面的代碼進行重構,首先給出三個解決方案:
2. 靜態代理
最簡單的解決方案就是使用靜態代理模式了,我們單獨爲 GreetingImpl 這個類寫一個代理類:
01 |
public class GreetingProxy implements Greeting { |
03 |
private GreetingImpl greetingImpl; |
05 |
public GreetingProxy(GreetingImpl greetingImpl) { |
06 |
this .greetingImpl = greetingImpl; |
10 |
public void sayHello(String name) { |
12 |
greetingImpl.sayHello(name); |
16 |
private void before() { |
17 |
System.out.println( "Before" ); |
20 |
private void after() { |
21 |
System.out.println( "After" ); |
就用這個 GreetingProxy 去代理 GreetingImpl,下面看看客戶端如何來調用:
3 |
public static void main(String[] args) { |
4 |
Greeting greetingProxy = new GreetingProxy( new GreetingImpl()); |
5 |
greetingProxy.sayHello( "Jack" ); |
這樣寫沒錯,但是有個問題,XxxProxy 這樣的類會越來越多,如何才能將這些代理類儘可能減少呢?最好只有一個代理類。
這時我們就需要使用 JDK 提供的動態代理了。
3. JDK 動態代理
01 |
public class JDKDynamicProxy implements InvocationHandler { |
03 |
private Object target; |
05 |
public JDKDynamicProxy(Object target) { |
09 |
@SuppressWarnings ( "unchecked" ) |
10 |
public <T> T getProxy() { |
11 |
return (T) Proxy.newProxyInstance( |
12 |
target.getClass().getClassLoader(), |
13 |
target.getClass().getInterfaces(), |
19 |
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { |
21 |
Object result = method.invoke(target, args); |
26 |
private void before() { |
27 |
System.out.println( "Before" ); |
30 |
private void after() { |
31 |
System.out.println( "After" ); |
客戶端是這樣調用的:
3 |
public static void main(String[] args) { |
4 |
Greeting greeting = new JDKDynamicProxy( new GreetingImpl()).getProxy(); |
5 |
greeting.sayHello( "Jack" ); |
這樣所有的代理類都合併到動態代理類中了,但這樣做仍然存在一個問題:JDK 給我們提供的動態代理只能代理接口,而不能代理沒有接口的類。有什麼方法可以解決呢?(假如一個類沒有接口,如果想使用AOP,可以使用CGLib)
4. CGLib 動態代理
我們使用開源的 CGLib 類庫可以代理沒有接口的類,這樣就彌補了 JDK 的不足。CGLib 動態代理類是這樣玩的:
01 |
public class CGLibDynamicProxy implements MethodInterceptor { |
03 |
private static CGLibDynamicProxy instance = new CGLibDynamicProxy(); |
05 |
private CGLibDynamicProxy() { |
08 |
public static CGLibDynamicProxy getInstance() { |
12 |
@SuppressWarnings ( "unchecked" ) |
13 |
public <T> T getProxy(Class<T> cls) { |
14 |
return (T) Enhancer.create(cls, this ); |
18 |
public Object intercept(Object target, Method method, Object[] args, MethodProxy proxy) throws Throwable { |
20 |
Object result = proxy.invokeSuper(target, args); |
25 |
private void before() { |
26 |
System.out.println( "Before" ); |
29 |
private void after() { |
30 |
System.out.println( "After" ); |
以上代碼中了 Singleton 模式,那麼客戶端調用也更加輕鬆了:
3 |
public static void main(String[] args) { |
4 |
Greeting greeting = CGLibDynamicProxy.getInstance().getProxy(GreetingImpl. class ); |
5 |
greeting.sayHello( "Jack" ); |
到此爲止,我們能做的都做了,問題似乎全部都解決了。但事情總不會那麼完美,而我們一定要追求完美!
老羅搞出了一個 AOP 框架,能否做到完美而優雅呢?請大家繼續往下看吧!
5. Spring AOP:前置增強、後置增強、環繞增強(編程式)
在 Spring AOP 的世界裏,與 AOP 相關的術語實在太多,往往也是我們的“攔路虎”,不管是看那本書或是技術文檔,在開頭都要將這些術語逐個灌輸給讀者。我想這完全是在嚇唬人了,其實沒那麼複雜的,大家放輕鬆一點。
我們上面例子中提到的 before() 方法,在 Spring AOP 裏就叫 Before Advice(前置增強)。有些人將 Advice 直譯爲“通知”,我想這是不太合適的,因爲它根本就沒有“通知”的含義,而是對原有代碼功能的一種“增強”。再說,CGLib 中也有一個 Enhancer
類,它就是一個增強類。
此外,像 after() 這樣的方法就叫 After Advice(後置增強),因爲它放在後面來增強代碼的功能。
如果能把 before() 與 after() 合併在一起,那就叫 Around Advice(環繞增強),就像漢堡一樣,中間夾一根火腿。
這三個概念是不是輕鬆地理解了呢?如果是,那就繼續吧!
我們下面要做的就是去實現這些所謂的“增強類”,讓他們橫切到代碼中,而不是將這些寫死在代碼中。
先來一個前置增強類吧:
1 |
public class GreetingBeforeAdvice implements MethodBeforeAdvice { |
4 |
public void before(Method method, Object[] args, Object target) throws Throwable { |
5 |
System.out.println( "Before" ); |
注意:這個類實現了 org.springframework.aop.MethodBeforeAdvice 接口,我們將需要增強的代碼放入其中。
再來一個後置增強類吧:
1 |
public class GreetingAfterAdvice implements AfterReturningAdvice { |
4 |
public void afterReturning(Object result, Method method, Object[] args, Object target) throws Throwable { |
5 |
System.out.println( "After" ); |
類似地,這個類實現了 org.springframework.aop.AfterReturningAdvice 接口。
最後用一個客戶端來把它們集成起來,看看如何調用吧:
03 |
public static void main(String[] args) { |
04 |
ProxyFactory proxyFactory = new ProxyFactory(); |
05 |
proxyFactory.setTarget( new GreetingImpl()); |
06 |
proxyFactory.addAdvice( new GreetingBeforeAdvice()); |
07 |
proxyFactory.addAdvice( new GreetingAfterAdvice()); |
09 |
Greeting greeting = (Greeting) proxyFactory.getProxy(); |
10 |
greeting.sayHello( "Jack" ); |
請仔細閱讀以上代碼及其註釋,您會發現,其實 Spring AOP 還是挺簡單的,對嗎?
當然,我們完全可以只定義一個增強類,讓它同時實現 MethodBeforeAdvice 與 AfterReturningAdvice 這兩個接口,如下:
01 |
public class GreetingBeforeAndAfterAdvice implements MethodBeforeAdvice, AfterReturningAdvice { |
04 |
public void before(Method method, Object[] args, Object target) throws Throwable { |
05 |
System.out.println( "Before" ); |
09 |
public void afterReturning(Object result, Method method, Object[] args, Object target) throws Throwable { |
10 |
System.out.println( "After" ); |
這樣我們只需要使用一行代碼,同時就可以添加前置與後置增強:
1 |
proxyFactory.addAdvice( new GreetingBeforeAndAfterAdvice()); |
剛纔有提到“環繞增強”,其實這個東西可以把“前置增強”與“後置增強”的功能給合併起來,無需讓我們同時實現以上兩個接口。
01 |
public class GreetingAroundAdvice implements MethodInterceptor { |
04 |
public Object invoke(MethodInvocation invocation) throws Throwable { |
06 |
Object result = invocation.proceed(); |
11 |
private void before() { |
12 |
System.out.println( "Before" ); |
15 |
private void after() { |
16 |
System.out.println( "After" ); |
環繞增強類需要實現 org.aopalliance.intercept.MethodInterceptor 接口。注意,這個接口不是 Spring 提供的,它是 AOP 聯盟(一個很牛逼的聯盟)寫的,Spring 只是借用了它。
在客戶端中同樣也需要將該增強類的對象添加到代理工廠中:
1 |
proxyFactory.addAdvice( new GreetingAroundAdvice()); |
好了,這就是 Spring AOP 的基本用法,但這只是“編程式”而已。Spring AOP 如果只是這樣,那就太傻逼了,它曾經也是一度宣傳用 Spring 配置文件的方式來定義 Bean 對象,把代碼中的 new 操作全部解脫出來。
6. Spring
AOP:前置增強、後置增強、環繞增強(聲明式)
先看 Spring 配置文件是如何寫的吧:
01 |
<? xml version = "1.0" encoding = "UTF-8" ?> |
02 |
< beans xmlns = "http://www.springframework.org/schema/beans" |
03 |
xmlns:xsi = "http://www.w3.org/2001/XMLSchema-instance" |
04 |
xmlns:context = "http://www.springframework.org/schema/context" |
05 |
xsi:schemaLocation="http://www.springframework.org/schema/beans |
06 |
http://www.springframework.org/schema/beans/spring-beans.xsd |
07 |
http://www.springframework.org/schema/context |
08 |
http://www.springframework.org/schema/context/spring-context.xsd"> |
11 |
< context:component-scan base-package = "aop.demo" /> |
14 |
< bean id = "greetingProxy" class = "org.springframework.aop.framework.ProxyFactoryBean" > |
15 |
< property name = "interfaces" value = "aop.Greeting" /> |
16 |
< property name = "target" ref = "greetingImpl" /> |
17 |
< property name = "interceptorNames" > |
19 |
< value >greetingAroundAdvice</ value > |
一定要閱讀以上代碼的註釋,其實使用 ProxyFactoryBean 就可以取代前面的 ProxyFactory,其實它們倆就一回事兒。我認爲 interceptorNames 應該改名爲 adviceNames 或許會更容易讓人理解,不就是往這個屬性裏面添加增強類嗎?
此外,如果只有一個增強類,可以使用以下方法來簡化:
3 |
< bean id = "greetingProxy" class = "org.springframework.aop.framework.ProxyFactoryBean" > |
4 |
< property name = "interfaces" value = "aop.Greeting" /> |
5 |
< property name = "target" ref = "greetingImpl" /> |
6 |
< property name = "interceptorNames" value = "greetingAroundAdvice" /> |
還需要注意的是,這裏使用了 Spring 2.5+ 的特性“Bean 掃描”,這樣我們就無需在 Spring 配置文件裏不斷地定義 <bean id="xxx" class="xxx"/> 了,從而解脫了我們的雙手。
看看這是有多麼的簡單:
2 |
public class GreetingImpl implements Greeting { |
2 |
public class GreetingAroundAdvice implements MethodInterceptor { |
最後看看客戶端吧:
3 |
public static void main(String[] args) { |
4 |
ApplicationContext context = new ClassPathXmlApplicationContext( "aop/demo/spring.xml" ); |
5 |
Greeting greeting = (Greeting) context.getBean( "greetingProxy" ); |
6 |
greeting.sayHello( "Jack" ); |
代碼量確實少了,我們將配置性的代碼放入配置文件,這樣也有助於後期維護。更重要的是,代碼只關注於業務邏輯,而將配置放入文件中。這是一條最佳實踐!
除了上面提到的那三類增強以外,其實還有兩類增強也需要了解一下,關鍵的時候您要能想得到它們才行。
7. Spring AOP:拋出增強
程序報錯,拋出異常了,一般的做法是打印到控制檯或日誌文件中,這樣很多地方都得去處理,有沒有一個一勞永逸的方法呢?那就是 Throws Advice(拋出增強),它確實很強,不信你就繼續往下看:
02 |
public class GreetingImpl implements Greeting { |
05 |
public void sayHello(String name) { |
06 |
System.out.println( "Hello! " + name); |
08 |
throw new RuntimeException( "Error" ); |
下面是拋出增強類的代碼:
02 |
public class GreetingThrowAdvice implements ThrowsAdvice { |
04 |
public void afterThrowing(Method method, Object[] args, Object target, Exception e) { |
05 |
System.out.println( "---------- Throw Exception ----------" ); |
06 |
System.out.println( "Target Class: " + target.getClass().getName()); |
07 |
System.out.println( "Method Name: " + method.getName()); |
08 |
System.out.println( "Exception Message: " + e.getMessage()); |
09 |
System.out.println( "-------------------------------------" ); |
拋出增強類需要實現 org.springframework.aop.ThrowsAdvice 接口,在接口方法中可獲取方法、參數、目標對象、異常對象等信息。我們可以把這些信息統一寫入到日誌中,當然也可以持久化到數據庫中。
這個功能確實太棒了!但還有一個更厲害的增強。如果某個類實現了 A 接口,但沒有實現 B 接口,那麼該類可以調用 B 接口的方法嗎?如果您沒有看到下面的內容,一定不敢相信原來這是可行的!
8. Spring AOP:引入增強
以上提到的都是對方法的增強,那能否對類進行增強呢?用 AOP 的行話來講,對方法的增強叫做 Weaving(織入),而對類的增強叫做 Introduction(引入)。而 Introduction
Advice(引入增強)就是對類的功能增強,它也是 Spring AOP 提供的最後一種增強。建議您一開始千萬不要去看《Spring Reference》,否則您一定會後悔的。因爲當您看了以下的代碼示例後,一定會徹底明白什麼纔是引入增強。
定義了一個新接口 Apology(道歉):
1 |
public interface Apology { |
3 |
void saySorry(String name); |
但我不想在代碼中讓 GreetingImpl 直接去實現這個接口,我想在程序運行的時候動態地實現它。因爲假如我實現了這個接口,那麼我就一定要改寫 GreetingImpl 這個類,關鍵是我不想改它,或許在真實場景中,這個類有1萬行代碼,我實在是不敢動了。於是,我需要藉助 Spring 的引入增強。這個有點意思了!
02 |
public class GreetingIntroAdvice extends DelegatingIntroductionInterceptor implements Apology { |
05 |
public Object invoke(MethodInvocation invocation) throws Throwable { |
06 |
return super .invoke(invocation); |
10 |
public void saySorry(String name) { |
11 |
System.out.println( "Sorry! " + name); |
以上定義了一個引入增強類,擴展了 org.springframework.aop.support.DelegatingIntroductionInterceptor 類,同時也實現了新定義的 Apology 接口。在類中首先覆蓋了父類的 invoke() 方法,然後實現了 Apology 接口的方法。我就是想用這個增強類去豐富 GreetingImpl 類的功能,那麼這個 GreetingImpl 類無需直接實現 Apology 接口,就可以在程序運行的時候調用 Apology 接口的方法了。這簡直是太神奇的!
看看是如何配置的吧:
01 |
<? xml version = "1.0" encoding = "UTF-8" ?> |
02 |
< beans xmlns = "http://www.springframework.org/schema/beans" |
03 |
xmlns:xsi = "http://www.w3.org/2001/XMLSchema-instance" |
04 |
xmlns:context = "http://www.springframework.org/schema/context" |
05 |
xsi:schemaLocation="http://www.springframework.org/schema/beans |
06 |
http://www.springframework.org/schema/beans/spring-beans.xsd |
07 |
http://www.springframework.org/schema/context |
08 |
http://www.springframework.org/schema/context/spring-context.xsd"> |
10 |
< context:component-scan base-package = "aop.demo" /> |
12 |
< bean id = "greetingProxy" class = "org.springframework.aop.framework.ProxyFactoryBean" > |
13 |
< property name = "interfaces" value = "aop.demo.Apology" /> |
14 |
< property name = "target" ref = "greetingImpl" /> |
15 |
< property name = "interceptorNames" value = "greetingIntroAdvice" /> |
16 |
< property name = "proxyTargetClass" value = "true" /> |
需要注意 proxyTargetClass 屬性,它表明是否代理目標類,默認爲 false,也就是代理接口了,此時 Spring 就用 JDK 動態代理。如果爲 true,那麼 Spring 就用 CGLib 動態代理。這簡直就是太方便了!Spring 封裝了這一切,讓程序員不在關心那麼多的細節。我們要向老羅同志致敬,您是我們心中永遠的 idol!
當您看完下面的客戶端代碼,一定會完全明白以上的這一切:
03 |
public static void main(String[] args) { |
04 |
ApplicationContext context = new ClassPathXmlApplicationContext( "aop/demo/spring.xml" ); |
05 |
GreetingImpl greetingImpl = (GreetingImpl) context.getBean( "greetingProxy" ); |
06 |
greetingImpl.sayHello( "Jack" ); |
08 |
Apology apology = (Apology) greetingImpl; |
09 |
apology.saySorry( "Jack" ); |
沒想到 saySorry() 方法原來是可以被 greetingImpl 對象來直接調用的,只需將其強制轉換爲該接口即可。
我們再次感謝 Spring AOP,感謝老羅給我們提供了這麼強大的特性!
其實,Spring AOP 還有很多精彩的地方,下一篇將介紹更多更有價值的 AOP 技術,讓大家得到更多的收穫。
未完,待續...
AOP 那點兒事(續集)
源碼下載