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就是代理对象调用的方法