读书人

AOP 学习, 包围通报

发布时间: 2012-10-26 10:30:59 作者: rapoo

AOP 学习, 包围通知
1. 包围通知 性能测试

org.aopalliance.intercept.MethodInterceptor

综合了前置通知和后置通知, 除了一个重要区别, 我们可以修改方法的返回值, 还可以阻止目标方法的执行,可以将目标方法的实现换成新的代码

public class MessageWriter {public void showMessage(){System.out.println("this is a test");}  }   

import org.aopalliance.intercept.MethodInterceptor;import org.aopalliance.intercept.MethodInvocation;import org.springframework.util.StopWatch;public class AroundInterceptor implements MethodInterceptor{public Object invoke(MethodInvocation invocation) throws Throwable{StopWatch sw=new StopWatch();sw.start(invocation.getMethod().getName());Object retVal=invocation.proceed();sw.stop();dumpInfo(invocation,sw.getTotalTimeMillis());return retVal;}private void dumpInfo(MethodInvocation invocation,long ms){java.lang.reflect.Method m=invocation.getMethod();Object target=invocation.getThis();Object[] args=invocation.getArguments();System.out.println("Execute method: "+m.getName());System.out.println("On Object of type: "+target.getClass().getName());System.out.println("with arguments: ");for(int x=0;x<args.length;x++){System.out.println("  >"+args[x]);System.out.print("\n");}System.out.println("took :"+ms + " ms");}  }

import org.springframework.aop.framework.ProxyFactory;public class test {public static void main(String[] args) {MessageWriter target =new MessageWriter();ProxyFactory pf=new ProxyFactory(target);pf.addAdvice(new AroundInterceptor()); MessageWriter proxy=(MessageWriter)pf.getProxy();proxy.showMessage();}                         }


结果
this is a testExecute method: showMessageOn Object of type: MessageWriterwith arguments: took :0 ms

读书人网 >软件架构设计

热点推荐