Macros

给我一支烟!请所有烦恼都能过往如云烟!

导航

深入浅出 spring AOP (一)

先不讨论AOP的各种名词,也不作各种AOP的比较,我将在例子中介绍各种名词。
1。先写一个javabean,就是target object。
package org.tatan.test;

public class MessageBean {
  public void write() {
         System.out.print("AOP example");
     }
}
2。写一个AOP的advice类
MethodInterceptor是AOP联盟的标准接口,它是最简单最实用的连接点(joinpoint),实现了around advice ,你可以在他返回前调用target的方法。
package org.tatan.test;
import org.aopalliance.intercept.MethodInterceptor;
import org.aopalliance.intercept.MethodInvocation;
public class MessageCode implements MethodInterceptor {

    public Object invoke(MethodInvocation invocation) throws Throwable {
        System.out.print("this is a ");
        Object returnValue = invocation.proceed();
       
        return returnValue ;
    }

}
3。把MessageCode advice weave 到proxy factory,proxy factory是整个架构的核心
先创建instance of MessageBean,然后创建代理的instance ,MessageCode advice 传递给的
addAdvice()方法,设置Target Object,调用getProxy()产生代理对象。
import org.springframework.aop.framework.ProxyFactory;

public class AOPExample {
  public static void main(String[] args) {
         MessageBean target = new MessageBean();
        
        
         ProxyFactory pf = new ProxyFactory();
    
         pf.addAdvice(new MessageCode());
         pf.setTarget(target);
    
         MessageBean proxy = (MessageBean) pf.getProxy();
        
         //输出原始信息
         target.write();
        //输出代理对象调用的信息
         proxy.write();
     }


}
4。classpath中加入cglib-nodep-2.1_2.jar ,spring.jar,aopalliance.jar,commons-logging.jar
结果
AOP example
this is a AOP example

原文链接:http://blogger.org.cn/blog/more.asp?name=hongrui&id=9918

posted on 2006-02-13 17:46  Macros  阅读(298)  评论(0)    收藏  举报