2019獨角獸企業重金招聘Python工程師標準>>>
5.4.1 ?從代理機制初探AOP
? ??? ??來看一個簡單的例子,當需要在執行某些方法時留下日志信息,可能會這樣寫:
import?java.util.logging.*;
public?class?HelloSpeaker{
pirvate?Logger?logger=Logger.getLogger(this.getClass().getName());public?void?hello(String?name){logger.log(Level.INFO,?"hello?method?starts…");//?方法開始執行時留下日志Sytem.out.println("hello,?"+name);?//?程序的主要功能Logger.log(Level.INFO,?"hello?method?ends…");//?方法執行完畢時留下日志}
}
? ??? ??在HelloSpeaker類中,當執行hello()方法時,程序員希望該方法執行開始與執行完畢時都留下日志。最簡單的做法是用上面的程序設計,在方法執行的前后加上日志動作。
? ??? ??可以使用代理(Proxy)機制來解決這個問題,有兩種代理方式:靜態代理(static proxy)和動態代理(dynamic proxy)。
? ??? ??在靜態代理的實現中,代理類與被代理的類必須實現同一個接口。在代理類中可以實現記錄等相關服務,并在需要的時候再呼叫被代理類。這樣被代理類就可以僅僅保留業務相關的職責了。
? ??? ??舉個簡單的例子,首先定義一個IHello接口,IHello.java代碼如下:
public?interface?IHello{public?void?hello(String?name);
}
? ? ? ? 然后讓實現業務邏輯的HelloSpeaker類實現IHello接口,HelloSpeaker.java代碼如下:
public?class?HelloSpeaker?implements?IHello{public?void?hello(String?name){System.out.println("hello,"+name);}
}
? ??? ??可以看到,在HelloSpeaker類中沒有任何日志的代碼插入其中,日志服務的實現將被放到代理類中,代理類同樣要實現IHello接口。
HelloProxy.java代碼如下:
public?class?HelloProxy?implements?IHello{private?Logger?logger=Logger.getLogger(this.getClass().getName());private?IHello?helloObject;public?HelloProxy(IHello?helloObject){this.helloObject=helloObject;}public?void?hello(String?name){log("hello?method?starts…");//?日志服務helloObject.hello(name);//?執行業務邏輯log("hello?method?ends…");//?日志服務}private?void?log(String?msg){logger.log(Level.INFO,msg);}
}
? ??? ??在HelloProxy類的hello()方法中,真正實現業務邏輯前后安排記錄服務,可以實際撰寫一個測試程序來看看如何使用代理類。
public?class?ProxyDemo{public?static?void?main(String[]?args){IHello?proxy=new?HelloProxy(new?HelloSpeaker());proxy.hello("Justin");}
}
? ??? ??程序運行結果:
hello,Justin
5.4.2 ?動態代理
? ??? ??要實現動態代理,同樣需要定義所要代理的接口。
IHello.java代碼如下:
public?interface?IHello{public?void?hello(String?name);
}
? ? ? ? 然后讓實現業務邏輯的HelloSpeaker類實現IHello接口。
HelloSpeaker.java代碼如下:
public?class?HelloSpeaker?implements?IHello{public?void?hello(String?name){System.out.println("Hello,"+name);}
}
? ??? ??與上例不同的是,這里要實現不同的代理類:
import?java.lang.reflect.InvocationHandler;
import?java.lang.reflect.Method;
public?class?LogHandler?implements?InvocationHandler{private?Object?sub;public?LogHandler()?{}public?LogHandler(Object?obj){sub?=?obj;}public?Object?invoke(Object?proxy,?Method?method,?Object[]?args)throws?Throwable{System.out.println("before?you?do?thing");method.invoke(sub,?args);System.out.println("after?you?do?thing");return?null;}
}
? ??? ??寫一個測試程序,使用LogHandler來綁定被代理類。
ProxyDemo.java代碼如下:
import?java.lang.reflect.Proxy;
public?class?ProxyDemo?{public?static?void?main(String[]?args)?{HelloSpeaker?helloSpeaker=new?HelloSpeaker();LogHandler?logHandler=new?LogHandler(helloSpeaker);Class?cls=helloSpeaker.getClass();IHello?iHello=(IHello)Proxy.newProxyInstance(cls.getClassLoader(),cls.getInterfaces(),logHandler);iHello.hello("Justin");}
}
? ??? ??程序運行結果:
before?you?do?thing
Hello,?Justin
after?you?do?thing
5.4.3 ?AOP術語與概念
1.cross-cutting concerns
? ??? ??在DynamicProxyDemo例子中,記錄的動作原先被橫切(Cross-cutting)到HelloSpeaker本身所負責的業務流程中。類似于日志這類的動作,如安全檢查、事務等服務,在一個應用程序中常被安排到各個類的處理流程之中。這些動作在AOP的術語中稱為cross-cutting concerns。如圖5.7所示,原來的業務流程是很單純的。?
?
圖5.7? 原來的業務流程
? ??? ??為了加入日志與安全檢查等服務,類的程序代碼中被硬生生地寫入了相關的Logging、Security程序片段,如圖5.8所示。?
?
圖5.8? 加入各種服務的業務流程
2.Aspect
? ??? ??將散落在各個業務類中的cross-cutting concerns收集起來,設計各個獨立可重用的類,這種類稱為Aspect。例如,在動態代理中將日志的動作設計為LogHandler類,LogHandler類在AOP術語中就是Aspect的一個具體實例。在需要該服務的時候,縫合到應用程序中;不需要服務的時候,也可以馬上從應用程序中脫離。應用程序中的可重用組件不用做任何的修改。例如,在動態代理中的HelloSpeaker所代表的角色就是應用程序中可重用的組件,在它需要日志服務時并不用修改本身的程序代碼。
5.4.4 ?通知Advice
? ??? ??Spring提供了5種通知(Advice)類型:Interception Around、Before、After Returning、Throw 和Introduction。它們分別在以下情況被調用:
Interception Around Advice:在目標對象的方法執行前后被調用。
Before Advice:在目標對象的方法執行前被調用。
After Returning Advice:在目標對象的方法執行后被調用。
Throw Advice:在目標對象的方法拋出異常時被調用。
Introduction Advice:一種特殊類型的攔截通知,只有在目標對象的方法調用完畢后執行。
創建一個Before Advice的Web項目,步驟如下。
① 創建一個Web項目,命名為“Spring_Advices”。
② 編寫Java類。
? ??? ??Before Advice會在目標對象的方法執行之前被呼叫。這個接口提供了獲取目標方法、參數及目標對象。
MethodBeforeAdvice接口的代碼如下:
import?java.lang.ref.*;
import?java.lang.reflect.Method;
public?interface?MethodBeforeAdvice{void?before(Method?method,?Object[]?args,?Object?target)?throws?Exception;
}
? ??? ??用實例來示范如何使用Before Advice。首先要定義目標對象必須實現的接口IHello。
IHello.java代碼如下:
public?interface?IHello{public?void?hello(String?name);
}
? ??? ??接著定義一個HelloSpeaker,實現IHello接口。
HelloSpeaker.java代碼如下:
public?class?HelloSpeaker?implements?IHello{public?void?hello(String?name){System.out.println("Hello,"+name);}
}
? ??? ??在對HelloSpeader不進行任何修改的情況下,想要在hello()方法執行之前可以記錄一些信息。有一個組件,但沒有源代碼,可對它增加一些日志的服務。
LogBeforeAdvice.java代碼如下:
import?java.lang.reflect.*;
import?java.util.logging.Level;
import?java.util.logging.Logger;
import?org.springframework.aop.MethodBeforeAdvice;
public?class?LogBeforeAdvice?implements?MethodBeforeAdvice{private?Logger?logger=Logger.getLogger(this.getClass().getName());public?void?before(Method?method,Object[]?args,Object?target)?throws?Exception{logger.log(Level.INFO,?"method?starts…"+method);}
}
③ 添加Spring開發能力。
applicationContext.xml的代碼如下:
<?xml?version="1.0"?encoding="UTF-8"?>
<beans?xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans?
http://www.springframework.org/schema/beans/spring-beans-2.0.xsd"><bean?id="logBeforeAdvice"?class="LogBeforeAdvice"?/><bean?id="helloSpeaker"?class="HelloSpeaker"?/><bean?id="helloProxy"class="org.springframework.aop.framework.ProxyFactoryBean"><property?name="proxyInterfaces"><value>IHello</value></property><property?name="target"><ref?bean="helloSpeaker"?/></property><property?name="interceptorNames"><list><value>logBeforeAdvice</value></list></property></bean>
</beans>
④ 運行程序,測試結果。
寫一個程序測試一下Before Advice的運作。
SpringAOPDemo.java代碼如下:
import?org.springframework.context.ApplicationContext;
import?org.springframework.context.support.FileSystemXmlApplicationContext;
public?class?SpringAOPDemo{public?static?void?main(String[]?args){ApplicationContext?context=new?FileSystemXmlApplicationContext("/WebRoot/WEB-INF/classes/applicationContext.xml");IHello?helloProxy=(IHello)context.getBean("helloProxy");helloProxy.hello("Justin");}
}
程序運行結果:
Hello,Justin
HelloSpeaker與LogBeforeAdvice是兩個獨立的類。對于HelloSpeaker來說,它不用知道LogBeforeAdvice的存在;而LogBeforeAdvice也可以運行到其他類之上。HelloSpeaker與LogBeforeAdvice都可以重復使用。
5.4.5 ?切入點Pointcut
創建一個切入點Pointcut項目,步驟如下。
① 創建一個Web項目,命名為“Spring_Pointcut”。
② 編寫Java類。
IHello.java代碼如下:
public?interface?IHello{public?void?helloNewbie(String?name);public?void?helloMaster(String?name);
}
HelloSpeaker類實現IHello接口。HelloSpeaker.java代碼如下:
public?class?HelloSpeaker?implements?IHello{public?void?helloNewbie(String?name){System.out.println("Hello,?"+name+"newbie!?");}public?void?helloMaster(String?name){System.out.println("Hello,?"+name+"master!?");}
}
③ 添加Spring開發能力。
applicationContext.xml的代碼。
<?xml?version="1.0"?encoding="UTF-8"?>
<beans?xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans?
http://www.springframework.org/schema/beans/spring-beans-2.0.xsd"><bean?id="logBeforeAdvice"?class="LogBeforeAdvice"?/><bean?id="helloAdvisor"class="org.springframework.aop.support.NameMatchMethodPointcutAdvisor"><property?name="mappedName"><value>hello*</value></property><property?name="advice"><ref?bean="logBeforeAdvice"?/></property></bean><bean?id="helloSpeaker"?class="HelloSpeaker"?/><bean?id="helloProxy"class="org.springframework.aop.framework.ProxyFactoryBean"><property?name="proxyInterfaces"><value>IHello</value></property><property?name="target"><ref?bean="helloSpeaker"?/></property><property?name="interceptorNames"><list><value>helloAdvisor</value></list></property></bean>
</beans>
④ 運行程序,測試結果。
SpringAOPDemo.java代碼如下:
import?org.springframework.context.ApplicationContext;
import?org.springframework.context.support.FileSystemXmlApplicationContext;
public?class?SpringAOPDemo?{public?static?void?main(String[]?args)?{ApplicationContext?context?=?new?FileSystemXmlApplicationContext("/WebRoot/WEB-INF/classes/applicationContext.xml");IHello?helloProxy?=?(IHello)?context.getBean("helloProxy");helloProxy.helloNewbie("Justin");helloProxy.helloMaster("Tom");}
}
程序運行結果:
Hello,?Justinnewbie!?
Hello,?Tommaster!
附:目錄《JavaEE基礎實用教程》筆記說明