Java編程中使用動態代理實現AOP功能
一、Java編程使用的背景
也不能算是使用的背景,最多只能算是一個在什么條件下面我想到了使用動態代理實現AOP的攔截功能):因為在項目中程序的結構是使用SOAP調用JNI,因此在SOAP服務端里面沒有任何實現代碼,僅僅是new一個JNI的對象,然后調用JNI對應的方法。但是在調用JNI方法之前需要對傳進JNI的JavaBean進行初始化,而且還需要記錄日志。而SOAP服務端的代碼是通過ant自動生成的,需要對他進行手工的修改,在修改過程中發現每一個方法里面都是相同的:記錄進入方法的日志、初始化JavaBean和記錄退出方法的日志,這寫東西都是通過拷貝粘貼來完成的,想到如果以后再加一個什么功能的時候又得每一個方法進行拷貝粘貼,而且方法的數量還不少,所以覺得這樣來實現是不科學的。示例代碼如下:
- public class SOAP{
- private JniInterface jni = null;
- private Log log = 。。。;
- public SOAP(){
- jni=new JniClass();
- }
- /**方法A**/
- public JavaBeanA aMethod(JavaBeanA javaBeanA){
- log.debug("進入A方法");
- //初始化JavaBean
- Init(javaBeanA);
- //調用JNI對應的方法
- JavaBeanA result = jni.aMethod(javaBeanA);
- log.debug("退出A方法");
- return result;
- }
- ……………………………………
- ……………………………………
- 等等,很多這樣的方法
- ……………………………………
- ……………………………………
- }
從示例代碼里面可以看出,除了調用JNI對應的方法不同之外,其他的都是相同的代碼,把所有的東西進行拷貝復制是不合理的。每當對SOAP進行修改,就必須將所有的方法重新拷貝粘貼。為了省去拷貝粘貼這一工序,所以使用動態代理實現AOP攔截共能。
二、實現AOP攔截
1.定義Interceptor接口
- public interface Interceptor {
- //在調用之前調用該方法
- public void before(InvokeJniInfo invInfo);
- //在調用之后調用該方法
- public void after(InvokeJniInfo invInfo);
- //出現異常之后調用該方法
- public void exceptionThrow(InvokeJniInfo invInfo);
- }
2. 定義 InvokeJniInfo 類
在Interceptor接口中的InvokeJniInfo類,該類的定義如下:
- public class InvokeJniInfo {
- //被代理的對象
- Object proxy;
- //被調用的方法
- Method method;
- //被調用方法的參數列表
- Object[] args;
- //調用之后的結果
- Object result;
- //拋出的異常
- Throwable exception;
- public InvokeJniInfo(Object proxy,
- Method method,
- Object[] args,
- Object result,
- Throwable exception){
- this.proxy = proxy;
- this.method = method;
- this.args = args;
- this.result = result;
- this.exception = exception;
- }
- …………………………………………………………
- …………………………………………………………
所有成員的get/set方法
…………………………………………………………
…………………………………………………………
}
從該類的成員變量可以知道,這個類使用來將調用函數的基本信息如代理的對象,調用的方法,調用方法的參數等信息傳遞給Interceptor,使得在Interceptor 之中可以通過使用該對象作出相應的攔截。
3.實現一個抽象的攔截器AbstractInterceptor
該攔截器實現了Interceptor接口,它里面的方法全都是空的,其目的是當某些攔截器只是需要實現三個方法中的一個方法或者兩個方法的時候,就可以繼承該抽象類,覆蓋需要的實現的方法就可以了。
4.實現日志記錄攔截器LogInterceptor
該攔截器主要是實現在調用之前記錄日志,調用之后記錄日志和出現異常的時候記錄日志。其代碼如下:
public class LogInterceptor implements Interceptor {
private Log log = LogFactory.getLog(“初始化Log” );
public void before(InvokeJniInfo invInfo) {
//調用InvokeJniInfo對象的Method的getName方法獲取方法名
log.debug("Enter the" + invInfo.getMethod().getName());
}
public void after(InvokeJniInfo invInfo) {
//調用InvokeJniInfo對象的Method的getName方法獲取方法名
log.debug("Exit the" + invInfo.getMethod().getName());
}
public void exceptionThrow(InvokeJniInfo invInfo) {
//調用InvokeJniInfo對象的Method的getName方法獲取方法名
log.error("Call the" + invInfo.getMethod().getName() + " has error!");
//調用InvokeJniInfo對象的Exception的getStackTrace方法獲取具體異常并記錄
- log.error(invInfo.getException().getStackTrace());
- }
- }
5.實現初始化JavaBean攔截器InitParamsInterceptor
該類繼承AbstractInterceptor,只需覆蓋before方法即可。其代碼如下:
- public class InitParamsInterceptor extends AbstractInterceptor {
- public void before(InvokeJniInfo invInfo) {
- if(invInfo.getArgs().length>0){
//初始化***個參數
- InitContainsObjectNullUtil.initContainsOutParameter(invInfo.getArgs()[0]);
- }
- }
- }
6.實現動態代理處理器InterceptorHandler
該類實現了java.lang.reflect.InvocationHandler接口。
public class InterceptorHandler implements InvocationHandler {
- private static Log log = LogFactory.getLog(InterceptorHandler.class);
//攔截器列表
private List interceptors = null;
//存放原始對象
private Object orginalObject;
//使用Proxy返回一個對象。注意這里傳進去的對象的對象必須實現一個接口
- public Object bind(Object obj) {
- this.orginalObject = obj;
- return Proxy.newProxyInstance(obj.getClass().getClassLoader(), obj
- .getClass().getInterfaces(), this);
- }
- public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
- Object result = null;
- Throwable ex = null;
- InvokeJniInfo invInfo = new InvokeJniInfo(proxy,method,args,result,ex);
- log.debug("Invoking Before Intercepors!");
//實現方法調用之前進行攔截的方法
- invokeInterceptorBefor(invInfo);
- try{
- log.debug("Invoking Proxy Method!");
- //調用方法
- result = method.invoke(orginalObject,args);
- invInfo.setResult(result);
- log.debug("Invoking After method!");
//實現方法調用之后進行攔截的方法
- invokeInterceptorAfter(invInfo);
- }catch(Throwable tr){
- invInfo.setException(tr);
- log.error("Invoking exceptionThrow method!");
//實現出現異常進行攔截的方法
- invokeInterceptorExceptionThrow(invInfo);
- }
- return result;
- }
//獲取攔截器列表
- private synchronized List getIntercetors(){
- if(null == interceptors){
- interceptors = new ArrayList();
//添加日志記錄攔截器
- interceptors.add(new LogInterceptor());
//添加初始化JavaBean攔截器
- interceptors.add(new InitParamsInterceptor());
//如果需要添加其他功能,可以很方便的添加其他的攔截器實現功能
- }
- return interceptors;
- }
- private void invokeInterceptorBefor(InvokeJniInfo invInfo){
- List interceptors = getIntercetors();
- int len = interceptors.size();
//遍歷所有攔截器,并調用攔截器的before方法
- for(int i = 0;i((Interceptor)interceptors.get(i)).before(invInfo);
- }
- }
- private void invokeInterceptorAfter(InvokeJniInfo invInfo){
- List interceptors = getIntercetors();
- int len = interceptors.size();
//遍歷所有攔截器,并調用攔截器的after方法
- for(int i = len - 1;i >= 0;i--){
- ((Interceptor)interceptors.get(i)).after(invInfo);
- }
- }
- private void invokeInterceptorExceptionThrow(InvokeJniInfo invInfo){
- List interceptors = getIntercetors();
- int len = interceptors.size();
//遍歷所有攔截器,并調用攔截器的exceptionThrow方法
- for(int i = len - 1;i >= 0;i--){
- ((Interceptor)interceptors.get(i)).exceptionThrow(invInfo);
- }
- }
- }
7.獲取動態代理對象工廠InterceptorFactory
- public class InterceptorFactory {
- private static Log log = LogFactory.getLog(InterceptorFactory.class);
- public static Object getClassInstance(String clzName) {
- Class cls;
- Object obj = null;
- try {
- cls = Class.forName(clzName);
- obj = (Object) cls.newInstance();
- } catch (Exception e) {
- log.error(e.getStackTrace());
- }
- return obj;
- }
- public static Object getInterceptorProxyedObject(String clzName) {
- InterceptorHandler aopHandler = new InterceptorHandler();
- Object obj = getClassInstance(clzName);
- return aopHandler.bind(obj);
- }
- }
- 8.修改以前的代碼,使用動態代理實現
- public class SOAP{
- private JniInterface jni = null;
- private Log log = 。。。;
- public SOAP(){
- jni=(JniInterface)InterceptorFactory.getInterceptorProxyedObject("JniClass");
- }
- /**方法A**/
- public JavaBeanA aMethod(JavaBeanA javaBeanA){
- return jni.aMethod(javaBeanA);
- }
……………………………………
……………………………………
等等,很多這樣的方法
……………………………………
……………………………………
}
從紅色代碼對比可以看出,省了很多代碼。
三、總結
1.必須徹底貫徹針對接口編成這一編程思想。
2.明白了這個,是不是也明白了Spring的AOP的實現了?以及為什么要使用Spring的AOP的時候必須使用他的BeanFactory呢?
【編輯推薦】