动态代理模拟Spring aop

4 篇文章 0 订阅

Aop:Aspect Oriented Programming 面向切面编程。
通过预编译的方法和运行期动态代理实现程序的一种衍生范型。利用aop可以对业务逻辑的各个部分进行隔离,从而使得业务逻辑各部分之间的耦合度降低,提高程序的重用性。
简单介绍完aop 的概念,我们就上代码。
这里我首先定义了一个工具类,用来绑定线程上的Connection对象,保证事务的一致性

import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.SQLException;

/**
 * Created on 20:53  02/11/2019
 * Description:
 *  连接的工具类,用于从数据源中获取一个连接,并实现和线程的绑定
 * @author Weleness
 */

public class ConnectionUtils {
    private  ThreadLocal<Connection> tl = new ThreadLocal<Connection>(); //使得创建的连接池对象都使用同一个事务

    private DataSource dataSource;

    public void setDataSource(DataSource dataSource) {
        this.dataSource = dataSource;
    }

    /**
     * @Method
     * Description:
     *  获取当前线程上的连接
     * @Author weleness
     *
     * @Return
     */
    public  Connection getThreadCon(){
        //1.先从ThreadLocal上获取
        Connection conn = tl.get();
        //2.判断当前线程上是否有连接
        if(conn == null){
            //3.从数据源中获取一个连接,并且存入ThreadLocal中
            try {
                conn = dataSource.getConnection();
            } catch (SQLException e) {
                e.printStackTrace();
            }
            tl.set(conn);
        }
        //4.返回当前线程上的连接
        return conn;
    }
    /**
     * @Method
     * Description:
     *  把链接和线程解绑
     * @Author weleness
     *
     * @Return
     */
    public void  removeConnection(){
        tl.remove();
    }
}

然后我又定义了一个控制事务的工具类

mport java.sql.SQLException;

/**
 * Created on 20:59  02/11/2019
 * Description:
 *  和事务管理相关的工具类,它包含了,开启事务,提交事务,回滚事务和释放连接
 * @author Weleness
 */

public class TransactionManager {
    private  ConnectionUtils connectionUtils;

    public void setConnectionUtils(ConnectionUtils connectionUtils) {
        this.connectionUtils = connectionUtils;
    }

    /**
     * @Method
     * Description:
     *  开启事务
     * @Author weleness
     *
     * @Return
     */
    public  void  beginTransaction(){
        try {
            connectionUtils.getThreadCon().setAutoCommit(false);
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
    /**
     * @Method
     * Description:
     *  开启事务
     * @Author weleness
     *  提交事务
     * @Return
     */
    public  void  commit(){
        try {
            connectionUtils.getThreadCon().commit();
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
    /**
     * @Method
     * Description:
     *  回滚事务
     * @Author weleness
     *
     * @Return
     */
    public  void rollback(){
        try {
            System.out.println("我要回滚啦");
            connectionUtils.getThreadCon().rollback();
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
    /**
     * @Method
     * Description:
     *  释放连接
     * @Author weleness
     *
     * @Return
     */
    public  void release(){
        try {
            connectionUtils.getThreadCon().close();//连接归还连接池
            connectionUtils.removeConnection(); // 解绑
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
}

然后。定义了一个BeanFactory工厂对象,这个类与前面两个组合起来使用动态代理来模拟aop支持事务的方式。

在这里插入代码片import service.IAccountService;
import utils.TransactionManager;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

/**
 * Created on 23:14  02/11/2019
 * Description:
 * 用于创建service的代理对象的工厂
 *
 * @author Weleness
 */

public class BeanFactory {
    private IAccountService accountService;
    private TransactionManager txManager;

    public void setTxManager(TransactionManager txManager) { // 匿名内部类引用外部类的对象只能引用final类型的
        this.txManager = txManager;
    }

    public  final void setAccountService(IAccountService accountService) {
        this.accountService = accountService;
    }

    /**
     * @Method Description:
     * 获取service代理对象
     * 通过动态代理给service绑定事务
     * @Author weleness
     * @Return
     */
    public IAccountService getAccountService() {
    return  (IAccountService)  Proxy.newProxyInstance(accountService.getClass().getClassLoader(), accountService.getClass().getInterfaces(), new InvocationHandler() {
            /**
             * @Method
             * Description:
             *  添加事务的支持
             * @Author weleness
             * []
             * @Return service.IAccountService
             */
            @Override
            public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
                Object rtValue = null;//方法可能有返回值,定义一个变量接收这个返回值
                try {
                    //1.开启事务
                    txManager.beginTransaction();
                    //2.执行操作
                    rtValue = method.invoke(accountService, args);
                    System.out.println("e");
                    //3.提交事务
                    txManager.commit();
                    //4.返回结果
                    return rtValue;
                } catch (Exception e) {
                    //5.回滚操作
                    txManager.rollback();
                } finally {
                    //6.释放资源
                    System.out.println("释放");
                    txManager.release();
                }
                return null;
            }
        });
    }
}

xml文件中的配置信息

 <!--配置代理的service -->
    <bean id="proxyAccountService" factory-bean="beanFactory" factory-method="getAccountService">

    </bean>
    <!--配置beanfactory -->
    <bean id="beanFactory" class="factory.BeanFactory">
        <property name="accountService" ref="accountService">

        </property>
        <!--注入事务管理器 -->
        <property name="txManager" ref="txManager">

        </property>
    </bean>
    <!--配置service对象 -->
    <bean id="accountService" class="service.impl.IAccountServiceImpl">
        <property name="dao" ref="Accountdao">

        </property>
    </bean>
    <!--配置dao对象对象 -->
    <bean id="Accountdao" class="dao.impl.IAccountDaoImpl">
        <property name="qr" ref="qr">

        </property>
        <!-- 注入ConnctionUtiles-->
        <property name="connectionUtils" ref="connectionUtils">

        </property>
    </bean>
    <!--配置数据库连接池对象 -->
    <bean id="qr" class="org.apache.commons.dbutils.QueryRunner" scope="prototype">
    </bean>
    <!-- 配置数据源-->
    <bean id="dataSource" class="org.apache.tomcat.dbcp.dbcp.BasicDataSource">
        <!--链接数据库的必备信息 -->
        <property name="url" value="jdbc:mysql://localhost:3306/account?serverTimezone=UTC">

        </property>
        <property name="username" value="root">

        </property>
        <property name="password" value="8761797">

        </property>
        <property name="driverClassName" value="com.mysql.jdbc.Driver">

        </property>
    </bean>
    <!--配置Connection的工具类 -->
    <bean id="connectionUtils" class="utils.ConnectionUtils">
        <!--注入数据源 -->
        <property name="dataSource" ref="dataSource">

        </property>
    </bean>
    <!-- 配置事务管理器-->
    <bean id="txManager" class="utils.TransactionManager">
        <property name="connectionUtils" ref="connectionUtils">

        </property>
    </bean>

业务层中需要事务支持的方法(切入点)

@Override
    public void transfer(String sourceName, String targetName, float money) {

        //1.根据名称查询转出账户
        Account source = dao.findAccountByName(sourceName);
        //2.根据名称查询转入账户
        Account target = dao.findAccountByName(targetName);
        //3.转出账户减钱
        source.setMoney(source.getMoney() - money);
        //4.转入账户加钱
        target.setMoney(target.getMoney() + money);
        //5.更新转出账户
        dao.updateAccount(source);
        //6.更新转入账户
        dao.updateAccount(target);
        int i = 9/0;//用于测试事务是否成功
    }

junit整合spring的测试类

/**
 * Created on 17:19  31/10/2019
 * Description:
 *
 * @author Weleness
 */

import domain.Account;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import service.IAccountService;

/**
 * @Method Description:
 * 使用junit 单元测试:测试我们的配置
 * @Author weleness
 * @Return
 */
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = "classpath:applicationContext.xml")
public class test {
    @Autowired
    @Qualifier("proxyAccountService")
    private IAccountService as;

   @Test
    public  void  testTransfer(){
        as.transfer("aaa","bbb",100);
    }
}

运行截图。在这里插入图片描述
这里可以看出来,通过动态代理模拟aop给方法绑定事务成功了。在这里博主踩了个小坑。发出来给大家看一下,不要踩博主踩过的坑。

  public IAccountService getAccountService() {
   accountService = (IAccountService) Proxy.newProxyInstance(accountService.getClass().getClassLoader(), accountService.getClass().getInterfaces(), new InvocationHandler() {
            /**
             * @Method
             * Description:
             *  添加事务的支持
             * @Author weleness
             * []
             * @Return service.IAccountService
             */
            @Override
            public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
                Object rtValue = null;
                try {

                    //1.开启事务
                    txManager.beginTransaction();
                    //2.执行操作
                    rtValue = method.invoke(accountService, args);
                    System.out.println("e");
                    //3.提交事务
                    txManager.commit();
                    //4.返回结果
                    return rtValue;
                } catch (Exception e) {
                    //5.回滚操作
                    txManager.rollback();
                } finally {
                    //6.释放资源
                    System.out.println("释放");
                    txManager.release();
                }
                return null;
            }
        });
    return accountService;
    }
}

在这里面。如果不通过一个被代理类的参数去接受方法的返回值,方法是不会被调用的。所以博主让上面的accoutService来接受这个方法的返回值。结果。。

sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
	at java.lang.reflect.Method.invoke(Method.java:498)
	at factory.BeanFactory$1.invoke(BeanFactory.java:55)
	at com.sun.proxy.$Proxy14.transfer(Unknown Source)
	at sun.reflect.GeneratedMethodAccessor1.invoke(Unknown Source)
	at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
	at java.lang.reflect.Method.invoke(Method.java:498)
	at factory.BeanFactory$1.invoke(BeanFactory.java:55)
	at com.sun.proxy.$Proxy14.transfer(Unknown Source)
	at sun.reflect.GeneratedMethodAccessor1.invoke(Unknown Source)
	at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
	at java.lang.reflect.Method.invoke(Method.java:498)
	at factory.BeanFactory$1.invoke(BeanFactory.java:55)
	at com.sun.proxy.$Proxy14.transfer(Unknown Source)
	at sun.reflect.GeneratedMethodAccessor1.invoke(Unknown Source)
	at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
	at java.lang.reflect.Method.invoke(Method.java:498)
	at factory.BeanFactory$1.invoke(BeanFactory.java:55)
	at com.sun.proxy.$Proxy14.transfer(Unknown Source)
	at sun.reflect.GeneratedMethodAccessor1.invoke(Unknown Source)


对。。它递归了,当时博主就懵了。。然后经过debug发现,由于用这个对象接收动态代理方法的返回值,又将这个对象传递给test类中的对象,相当于它在这个类中调用了一次这个方法,传出去外面的时候又调用了一次方法,这样就造成了递归。
所以 直接返回一个新的对象就好了呢。

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Spring AOP中,动态代理是实现AOP的一种方式。Spring AOP使用了Java的动态代理机制来创建代理对象,并将切面逻辑织入到目标对象的方法调用中。 动态代理是在运行时生成代理对象的一种机制。它不需要在编写代码时就确定要代理的类和方法,而是在运行时根据需要创建代理对象。在Spring AOP中,主要有两种类型的动态代理:基于接口的代理和基于类的代理。 1. 基于接口的代理(JDK动态代理):当目标对象实现了至少一个接口时,Spring AOP使用JDK动态代理来生成代理对象。JDK动态代理通过实现目标对象所实现的接口来生成代理对象,在调用代理对象的方法时,会通过InvocationHandler接口将方法调用转发给实际的目标对象。 2. 基于类的代理(CGLIB动态代理):当目标对象没有实现任何接口时,Spring AOP使用CGLIB动态代理来生成代理对象。CGLIB动态代理通过继承目标对象生成一个子类,并覆盖其中的方法来实现代理。调用代理对象的方法时,会先进入子类的方法,然后再调用目标对象的方法。 使用动态代理可以实现对目标对象的拦截和增强,而不需要修改目标对象的源代码。代理对象可以在目标对象的方法执行前、执行后或执行过程中插入额外的逻辑,例如日志记录、性能统计、事务管理等。 需要注意的是,动态代理只能对公共方法进行拦截,对私有方法、静态方法或final方法无法进行拦截。同时,动态代理也只能拦截通过代理对象调用的方法,直接通过目标对象调用方法时无法实现拦截和增强。 总结来说,Spring AOP使用动态代理来实现切面逻辑的织入,可以通过JDK动态代理或CGLIB动态代理来生成代理对象,并将切面逻辑应用到目标对象的方法调用中。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值