spring的jdk代理类小案例

spring的JDK代理类前文有介绍地址:https://blog.csdn.net/one_dayR/article/details/80103731

本文是为了帮助理解spring的JDK代理类的思想

需要的jar:

spring.jar和commons-logging.jar

目标类Dao接口:
public interface PersonDao {
	public void savePerson();
	public void updatePerson();
}
目标类DaoImp实现:

public class PersonDaoImpl implements PersonDao{
	public void savePerson() {
		System.out.println("save person");
	}

	public void updatePerson() {
		// TODO Auto-generated method stub
		System.out.println("update person");
	}
}
事务:

public class Transaction {
	public void beginTransaction(){
		System.out.println("begin transaction");
	}
	public void commit(){
		System.out.println("commit");
	}
}
代理类:
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;

public class MyInterceptor implements InvocationHandler{
	private Object target;//目标类
	private Transaction transaction;
	
	
	public MyInterceptor(Object target, Transaction transaction) {
		super();
		this.target = target;
		this.transaction = transaction;
	}

	
	public Object invoke(Object proxy, Method method, Object[] args)
			throws Throwable {
		String methodName = method.getName();
		if("savePerson".equals(methodName)||"updatePerson".equals(methodName)
				||"deletePerson".equals(methodName)){
			this.transaction.beginTransaction();//开启事务
			method.invoke(target);//调用目标方法
			this.transaction.commit();//事务的提交
		}else{
			method.invoke(target);
		}
		return null;
	}
}
测试:
import java.lang.reflect.Proxy;

import org.junit.Test;


public class JDKProxyTest {
	@Test
	public void testJDKProxy(){
		/**
		 * 1、创建一个目标对象
		 * 2、创建一个事务
		 * 3、创建一个拦截器
		 * 4、动态产生一个代理对象
		 */
		Object target = new PersonDaoImpl();
		Transaction transaction = new Transaction();
		MyInterceptor interceptor = new MyInterceptor(target, transaction);
		/**
		 * 1、目标类的类加载器
		 * 2、目标类实现的所有的接口
		 * 3、拦截器
		 */
		PersonDao personDao = (PersonDao)Proxy.newProxyInstance(target.getClass().getClassLoader(), 
				target.getClass().getInterfaces(), interceptor);
		//personDao.savePerson();
		personDao.updatePerson();
	}
}
总结三个问题:

 1、拦截器的invoke方法是在时候执行的?
    当在客户端,代理对象调用方法的时候,进入到了拦截器的invoke方法
 2、代理对象的方法体的内容是什么?
    拦截器的invoke方法的内容就是代理对象的方法的内容
 3、拦截器中的invoke方法中的参数method是谁在什么时候传递过来的?
     代理对象调用方法的时候,进入了拦截器中的invoke方法,所以invoke方法中的参数method就是代理对象调用的方法


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值