44543

package CglibProxy;

import java.lang.reflect.Method;

import org.springframework.asm.AnnotationVisitor;
import org.springframework.asm.Attribute;
import org.springframework.asm.Label;
import org.springframework.asm.MethodVisitor;


import net.sf.cglib.proxy.Enhancer;
import net.sf.cglib.proxy.MethodInterceptor;
import net.sf.cglib.proxy.MethodProxy;

public class MyInvocationHandler implements MethodInterceptor{
	private Object target;//代理真实的实现类
	private Transcation transaction;//事务
	
	public MyInvocationHandler(Object target, Transcation transaction) {
		this.target = target;
		this.transaction = transaction;
	}
	
	/**
	 * 创建代理对象
	 * <p>Title: createProxy</p>
	 * <p>Description: </p>
	 * @return
	 */
	public Object createProxy(){
		Enhancer enhancer = new Enhancer();
		enhancer.setCallback(this);//this代表拦截器对象
		enhancer.setSuperclass(target.getClass());//设置代理类的父类为目标类
		return enhancer.create();
	}
	
	
	
	/**
	 * 该方法的内容和jdkpoxy中的invoke方法的内容是一样的
	 */
	public Object intercept(Object arg0, Method method,  Object[] args,
			MethodProxy arg3) throws Throwable { 
		this.transaction.beginTransaction();
		method.invoke(this.target, args);
		this.transaction.commit();
		return null;
	}


	
}


package CglibProxy;

public class TestProxy {
   
	public static void main(String[] args) {
	 PersonDaoImpl target = new PersonDaoImpl();
	 Transcation transaction = new Transcation();
	 MyInvocationHandler myInvocationHandler = new MyInvocationHandler(target, transaction);
	 //调用动态生成的target对象PersonDaoImpl
	 PersonDaoImpl proxy = (PersonDaoImpl)myInvocationHandler.createProxy();
	 proxy.savePerson();
	}
	
}



你可能感兴趣的:(44543)