Spring-Aop学习的前提——动态代理2

在这里我们再写一个jdk动态代理的例子:
接口:

public interface PersonDao {
    public void savePerson();
}

接口实现类:

public class PersonDaoImpl implements PersonDao{
    @Override
    public void savePerson() {
        // TODO Auto-generated method stub
        System.out.println("savePerson...........");
    }

}

事务类:

public class Transaction {
    public void beginTransaction() {
        System.out.println("begin Transaction");
    }
    public void commit() {
        System.out.println("commit...");
    }
}

拦截类:(也就是InvocationHandler类)

/**
 * 拦截器
 * @author user
 *作用:1。目标类导进来
 *  2.事务导进来
 *  3.invoke方法完成:
 *      (1):开启事务
 *      (2):调用目标对象方法
 *      (3):事务提交
 *
 */
public class MyInterceptor implements InvocationHandler{
    private Object target; //目标类
    private Transaction transcation;//事务
    public MyInterceptor(Object target, Transaction transcation) {
        super();
        this.target = target;
        this.transcation = transcation;
    }
    //代理实例     
    @Override
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
        Object result = null;
        String methodName = method.getName();
        if("savePerson".equals(methodName) || "updatePerson".equals(methodName)|| "deletePrrson".equals(methodName)) {
            this.transcation.beginTransaction(); //开启事务
            method.invoke(target);//调用目标方法
            this.transcation.commit();//事务的提交
        }else {
            result = method.invoke(target,args);
        }
        return result;
    }

测试类:

/**
 * 
 * @author user
 *  1.拦截器的Invoke方法是在什么时候执行
 *  在客户端,代理对象调用的时候  personDao.savePerson(); 进入了拦截器的Invoke方法
 *  
 *  2.代理对象的方法体的内容
 *      拦截器的invoke方法的内容就是代理对象的方法的内容
 *  3.拦截器的Invoke方法中的参数method是谁在什么时候传过来的
 *      代理对象调用方法的时候进入了拦截器中的invoke方法,所以invoke方法的参数method就是代理对象调用的方法
 *
 */
public class JdkProxyText {
    public void textJdkProxy() {
        /**
         * 1.创建目标类
         * 2.创建事务
         * 3.创建拦截器
         * 4.动态产生一个代理对象
         */
        Object target = new PersonDaoImpl();
        Transaction transcation = new Transaction();
        MyInterceptor myInterceptor = new MyInterceptor(target, transcation);
        //三个参数   目标类的类加载器
        //      目标类实现的所有接口
        //      拦截器
        PersonDao personDao = (PersonDao) Proxy.newProxyInstance(target.getClass().getClassLoader(), target.getClass().getInterfaces(), myInterceptor);
        personDao.savePerson();
    }
    public static void main(String[] args) {
        JdkProxyText text = new JdkProxyText();
        text.textJdkProxy();
    }
}

猜你喜欢

转载自blog.csdn.net/qq_39411208/article/details/81585763