做一些Spring AOP做过的事,封装 jdk动态代理成为一个黑盒子

 

怎么使用eclise 抽取方法,请看  利用eclipse 抽取代码片段为方法

 

抽取完成之后,还需要

① 将Collection.class换成  target.getClass(),target是Object的,可以来代理所有的对象

② Proxy.newProxyInstance(target.getClass().getClassLoader(),

target.getClass().getInterfaces(),

new InvocationHander(){

    invoke(Object proxy,Method method,Object[] args) {

             advice.beforeMethod(method);//我们在使用Spring AOP时,只写 beforeMethod类似的交叉功能的实现

            Object  retVal=  proxy.invoke(target,args);

            advice.afterMethod(method);//我们在使用Spring AOP时,只写 afterMethod 类似的交叉功能方法的实现

             return  retVal;

}

}

)

 

 

我通过eclipse封装好的黑匣子

	private static Object getProxy(final Object target,final Advice advice) {
		Object proxy3=(Collection)Proxy.newProxyInstance(target.getClass().getClassLoader(), 
				target.getClass().getInterfaces(),
				new InvocationHandler() {
				@Override
				public Object invoke(Object proxy, Method method, Object[] args)
						throws Throwable {
					
				/*	long beginTime=System.currentTimeMillis();
					Object retVal=method.invoke(target, args);
					long endTime=System.currentTimeMillis();
					System.out.println(method.getName()+"执行时间 "+(endTime-beginTime)+" 毫秒");
					return retVal;*/
					advice.beforeMethod(method);
					Object retVal=method.invoke(target, args);
					advice.afterMethod(method);
					return retVal;
				}
		});
		return proxy3;
	}
	

 

 

这么调用黑匣子

final ArrayList  target=new ArrayList();//类变量
		
Collection proxy3 = (Collection) getProxy(target,new MyAdvice());

 

 

我写的MyAdvice,其中Advice将来由Spring定义好,里面会有各种位置的方法,如afterMethod,beforeMethod, after throwing  , around

package com.itcast.day3;

import java.lang.reflect.Method;

public class MyAdvice implements Advice {
	long beginTime=0;
	@Override
	public void beforeMethod(Method method) {
		System.out.println("到传智播客学习啦...");
		beginTime=System.currentTimeMillis();

	}

	@Override
	public void afterMethod(Method method) {
		System.out.println("从传智播客毕业工作啦...");
		long endTime=System.currentTimeMillis();
		System.out.println(method.getName()+"执行时间 "+(endTime-beginTime)+" 毫秒");
	}

}

 

将来使用Spring  AOP时,只做两件事,

① 确定目标对象target

② 写MyAdvice (其实就是实现Spring 提供的Advice接口中的  beforeMethod, afterMethod方法)

posted @ 2016-04-13 17:51  刘江龙  阅读(245)  评论(0编辑  收藏  举报