`
隐形的翅膀
  • 浏览: 484236 次
  • 性别: Icon_minigender_1
  • 来自: 北京
社区版块
存档分类
最新评论

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 test
Execute method: showMessage
On Object of type: MessageWriter
with arguments: 
took :0 ms
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics