Spring AOP 本質(1)

Spring AOP 本質(1)
 
AOP本質是攔截,攔截的本質是代理,代理分動態和靜態,靜態代理很簡單,功能有限,應用不是很普遍,Spring中主要用的動態代理。
 
用Spring作開發,AOP的實現僅僅是編程實現一些接口,而後配置一下便可。這個能夠參看「 Spring AOP 模型」一文。
 
爲何配置一下便可,究竟Spring框架內部作了如何的處理,實現了代理。下面能夠看看下面的例子就明白了。
 
/**
* 被代理類
*/

public class MessageWriter{
     /**
     * 業務方法
     */

     public void writeMessage() {
        System.out.print( "World");
    }
}
 
import org.aopalliance.intercept.MethodInterceptor;
import org.aopalliance.intercept.MethodInvocation;

/**
* 實現包圍通知,實際就是方法攔截器,MethodInterceptor是AOP聯盟定義的接口.
*/

public class MessageDecorator implements MethodInterceptor {

     public Object invoke(MethodInvocation invocation) throws Throwable {
        System.out.print( "Hello ");
        Object retVal = invocation.proceed();
        System.out.println( "!");
         return retVal;
    }
}
 
import org.springframework.aop.framework.ProxyFactory;

/**
* AOP測試
*/

public class HelloWorldAOPExample {

     public static void main(String[] args) {
         //目標對象(被代理的對象)
        MessageWriter target = new MessageWriter();
        
         //產生一個代理工廠
        ProxyFactory pf = new ProxyFactory();
         //添加代理工廠的攔截器
        pf.addAdvice( new MessageDecorator());
         //設置被代理對象
        pf.setTarget(target);

         //獲取一個代理實例
        MessageWriter proxy = (MessageWriter) pf.getProxy();
        
         //從目標對象直接輸出信息
        target.writeMessage();
        System.out.println( "\n------------");
         //從代理對象輸出信息
        proxy.writeMessage();
    }
}
 
例子中用ProxyFactory類來建立目標對象的代理,同時織入通知。經過調用addAdvice(new MessageDecorator()),把MessageDecorator通知傳給ProxyFactory,而後經過調用setTarget(target)設定織入的目標對象。設定了目標對象,也織入了通知,就能夠調用ProxyFactory.getProxy()來得到一個代理對象。
 
運行結果:
- Using JDK 1.4 collections
World
------------
Hello World!

Process finished with exit code 0
 
從中能夠看到,Spring的代理很牛,不必定要求代理和被代理類都要實現同一個接口,Spring能夠代理任何的類,固然final類除外,由於final類不容許繼承。
 
參考資料:
《Pro Spring》
相關文章
相關標籤/搜索