转账方法演示事务问题及AOP保持事务一致性

事务控制演示

pom文件配置如下:

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>com.ethan</groupId>
    <artifactId>day03_eesy_01account</artifactId>
    <version>1.0-SNAPSHOT</version>
    <packaging>jar</packaging>

    <dependencies>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context</artifactId>
            <version>5.2.3.RELEASE</version>
        </dependency>

        <dependency>
            <groupId>commons-dbutils</groupId>
            <artifactId>commons-dbutils</artifactId>
            <version>1.7</version>
        </dependency>

        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>8.0.18</version>
        </dependency>

        <dependency>
            <groupId>c3p0</groupId>
            <artifactId>c3p0</artifactId>
            <version>0.9.1.2</version>
        </dependency>

        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.13</version>
            <scope>test</scope>
        </dependency>

        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-test</artifactId>
            <version>5.2.3.RELEASE</version>
            <scope>test</scope>
        </dependency>

    </dependencies>

</project>

spring容器配置如下:

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:context="http://www.springframework.org/schema/context"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
        http://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/context
        http://www.springframework.org/schema/context/spring-context.xsd">

    <context:annotation-config/>

    <!--配置Service对象-->
    <bean id="accountService" class="com.ethan.service.impl.AccountServiceImpl">
        <!--注入DAO对象-->
        <property name="accountDAO" ref="accountDAO"></property>
    </bean>
    <!--配置DAO对象-->
    <bean id="accountDAO" class="com.ethan.dao.impl.AccountDAOImpl">
        <property name="runner" ref="runner"></property>
    </bean>

    <bean id ="runner" class="org.apache.commons.dbutils.QueryRunner" scope="prototype">
        <!--注入数据源-->
        <constructor-arg name="ds" ref="dataSource"></constructor-arg>
    </bean>

    <!--配置数据源-->
    <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
        <!--连接数据库的必备信息-->
        <property name="driverClass" value="com.mysql.cj.jdbc.Driver"></property>
        <property name="jdbcUrl" value="jdbc:mysql://localhost:3306/eesy?serverTimezone=GMT%2b8"></property>
        <property name="user" value="root"></property>
        <property name="password" value="6540"></property>
    </bean>
</beans>

为了实现转账操作,先在持久层接口添加以下方法:

    /**
     * @param accountName
     * @return 没有结果则返回null,结果多于一个则抛出异常
     */
    Account findAccountByName(String accountName);

该方法实现如下:

    public Account findAccountByName(String accountName) {
        try {
            List<Account> accounts = runner.query("select * from account where name = ?", new BeanListHandler<Account>(Account.class), accountName);
            if(accounts == null || accounts.size() == 0) {
                return null;
            }
            if(accounts.size() > 1) {
                throw new RuntimeException("结果集不唯一,数据有问题");
            }
            return accounts.get(0);
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }

然后就可以在业务层实现转账操作:

    public void transfer(String sourceName, String targetName, Float money) {
        //1.根据名称查询转出账户
        //2.根据名称查询转入账户
        //3.转出账户减钱
        //4.转入账户加钱
        //5.更新转出账户
        //5.更新转入账户
        Account source = accountDAO.findAccountByName(sourceName);
        Account target = accountDAO.findAccountByName(targetName);
        source.setMoney(source.getMoney() - money);
        target.setMoney(target.getMoney() + money);
        accountDAO.updateAccount(source);
        accountDAO.updateAccount(target);
    }

因为以上操作由多个事务构成,如果在source账户更新后,在target账户更新前,程序产生异常,那么target账户得不到更新,这时不能保证事务的一致性。我们应该将以上几步操作合并为一个事务。为此,我们创建一个工具类ConnectionUtils来获取线程上的数据库连接:

在这里插入图片描述

package com.ethan.utils;

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

/**
 * @author Ethan
 * @date 2020/1/25 - 11:06
 * 连接的工具类,它用于从数据源中获取一个连接,并且实现和线程绑定
 */
public class ConnectionUtils {

    private ThreadLocal<Connection> tl = new ThreadLocal<Connection>();

    private DataSource dataSource;

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

    /**
     * 获取当前线程上的连接
     * @return
     */
    public Connection getThreadConnection() {
        try {
            //1.先从ThreadLocal上获取
            Connection conn = tl.get();
            //2.判断当前线程上是否有连接
            if(conn == null) {
                //3.从数据源中获取连接,并且存入ThreadLocal中
                conn = dataSource.getConnection();
                tl.set(conn);
            }
            return conn;
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * 把连接和线程解绑
     */
    public void removeConnection() {
    }
}

再创建一个类实现事务管理:

package com.ethan.utils;

import java.sql.SQLException;

/**
 * @author Ethan
 * @date 2020/1/25 - 11:16
 * 和事务管理相关的工具类,它包含了:开启事务、提交事务、回滚事务和释放连接
 */
public class TransactionManager {

    private ConnectionUtils connectionUtils;

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

    public void beginTransaction() {
        try {
            connectionUtils.getThreadConnection().setAutoCommit(false);
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    public void commit() {
        try {
            connectionUtils.getThreadConnection().commit();
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    public void rollback() {
        try {
            connectionUtils.getThreadConnection().rollback();
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    public void release() {
        try {
            connectionUtils.getThreadConnection().close();
            connectionUtils.removeConnection();
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
}

为了实现操作的原子性,我们要改造业务层实现类:

package com.ethan.service.impl;

import com.ethan.dao.AccountDAO;
import com.ethan.service.AccountService;
import com.ethan.service.domain.Account;
import com.ethan.utils.TransactionManager;

import java.util.List;

/**
 * @author Ethan
 * @date 2020/1/24 - 10:02
 */
public class AccountServiceImpl implements AccountService {

    private AccountDAO accountDAO;
    private TransactionManager txManager;

    public void setTxManager(TransactionManager txManager) {
        this.txManager = txManager;
    }

    public void setAccountDAO(AccountDAO accountDAO) {
        this.accountDAO = accountDAO;
    }

    public List<Account> findAllAccount() {
        try {
            txManager.beginTransaction();
            List<Account> accounts = accountDAO.findAllAccount();
            txManager.commit();
            return accounts;
        } catch (Exception e) {
            txManager.rollback();
            throw new RuntimeException(e);
        } finally {
            txManager.release();
        }
    }

    public Account findAccountById(Integer accountId) {
        try {
            txManager.beginTransaction();
            Account account = accountDAO.findAccountById(accountId);
            txManager.commit();
            return account;
        } catch (Exception e) {
            txManager.rollback();
            throw new RuntimeException(e);
        } finally {
            txManager.release();
        }
    }

    public void saveAccount(Account account) {
        try {
            txManager.beginTransaction();
            accountDAO.saveAccount(account);
            txManager.commit();
        } catch (Exception e) {
            txManager.rollback();
            throw new RuntimeException(e);
        } finally {
            txManager.release();
        }
    }

    public void updateAccount(Account account) {
        try {
            txManager.beginTransaction();
            accountDAO.updateAccount(account);
            txManager.commit();
        } catch (Exception e) {
            txManager.rollback();
            throw new RuntimeException(e);
        } finally {
            txManager.release();
        }
    }

    public void deleteAccount(Integer accountId) {
        try {
            txManager.beginTransaction();
            accountDAO.deleteAccount(accountId);
            txManager.commit();
        } catch (Exception e) {
            txManager.rollback();
            throw new RuntimeException(e);
        } finally {
            txManager.release();
        }
    }

    public void transfer(String sourceName, String targetName, Float money) {
        try {
            txManager.beginTransaction();
            Account source = accountDAO.findAccountByName(sourceName);
            Account target = accountDAO.findAccountByName(targetName);
            source.setMoney(source.getMoney() - money);
            target.setMoney(target.getMoney() + money);
            accountDAO.updateAccount(source);
            int a = 1/0;	//这时即使产生异常也不会导致事务前后状态的不一致
            accountDAO.updateAccount(target);
            txManager.commit();
        } catch (Exception e) {
            txManager.rollback();
            throw new RuntimeException(e);
        } finally {
            txManager.release();
        }
    }
}

我们在执行时,如果DAO中执行方法的同时,给QueryRunner注入Connection之后,它就会从连接中取一个,而现在不希望从连接中取,于是不再给runner注入Connection,但是这时DAO中的操作将没有Connection,这时我们在DAO中添加一个成员变量ConnectionUtils,并且在每个runner的方法中直接使用这个变量的connection

package com.ethan.dao.impl;

import com.ethan.dao.AccountDAO;
import com.ethan.service.domain.Account;
import com.ethan.utils.ConnectionUtils;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanHandler;
import org.apache.commons.dbutils.handlers.BeanListHandler;

import java.sql.SQLException;
import java.util.List;

/**
 * @author Ethan
 * @date 2020/1/24 - 10:08
 */
public class AccountDAOImpl implements AccountDAO {

    private QueryRunner runner;
    private ConnectionUtils connectionUtils;

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

    public void setRunner(QueryRunner runner) {
        this.runner = runner;
    }

    public List<Account> findAllAccount() {
        try {
            return runner.query(connectionUtils.getThreadConnection(), "select * from account", new BeanListHandler<Account>(Account.class));
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }

    public Account findAccountById(Integer accountId) {
        try {
            return runner.query(connectionUtils.getThreadConnection(), "select * from account where id = ?", new BeanHandler<Account>(Account.class), accountId);
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }

    public void saveAccount(Account account) {
        try {
            runner.update(connectionUtils.getThreadConnection(), "insert into account(name, money)values(? ,?)", account.getName(), account.getMoney());
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }

    public void updateAccount(Account account) {
        try {
            runner.update(connectionUtils.getThreadConnection(), "update account set name=?, money=? where id=?", account.getName(), account.getMoney(), account.getId());
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }

    public void deleteAccount(Integer accountId) {
        try {
            runner.update(connectionUtils.getThreadConnection(), "delete from account where id=?", accountId);
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }

    public Account findAccountByName(String accountName) {
        try {
            List<Account> accounts = runner.query(connectionUtils.getThreadConnection(), "select * from account where name = ?", new BeanListHandler<Account>(Account.class), accountName);
            if(accounts == null || accounts.size() == 0) {
                return null;
            }
            if(accounts.size() > 1) {
                throw new RuntimeException("结果集不唯一,数据有问题");
            }
            return accounts.get(0);
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }
}

工具类、持久层实现类依赖注入如下:

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:context="http://www.springframework.org/schema/context"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
        http://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/context
        http://www.springframework.org/schema/context/spring-context.xsd">

    <context:annotation-config/>

    <!--配置Service对象-->
    <bean id="accountService" class="com.ethan.service.impl.AccountServiceImpl">
        <!--注入DAO对象-->
        <property name="accountDAO" ref="accountDAO"></property>
        <property name="txManager" ref="txManager"></property>
    </bean>
    <!--配置DAO对象-->
    <bean id="accountDAO" class="com.ethan.dao.impl.AccountDAOImpl">
        <property name="runner" ref="runner"></property>
        <property name="connectionUtils" ref="connectionUtils"></property>
    </bean>

    <bean id ="runner" class="org.apache.commons.dbutils.QueryRunner" scope="prototype"></bean>

    <!--配置数据源-->
    <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
        <!--连接数据库的必备信息-->
        <property name="driverClass" value="com.mysql.cj.jdbc.Driver"></property>
        <property name="jdbcUrl" value="jdbc:mysql://localhost:3306/eesy?serverTimezone=GMT%2b8"></property>
        <property name="user" value="root"></property>
        <property name="password" value="0000"></property>
    </bean>

    <!--配置Connection的工具类 ConnectionUtils-->
    <bean id="connectionUtils" class="com.ethan.utils.ConnectionUtils">
        <property name="dataSource" ref="dataSource"></property>
    </bean>

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

AccountService的测试类:

package com.ethan.test;

import com.ethan.service.AccountService;
import com.ethan.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;

/**
 * @author Ethan
 * @date 2020/1/24 - 10:37
 * 使用Junit单元测试:测试我们的配置
 */

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = "classpath:bean.xml")
public class AccountServiceTest {

    @Autowired
    AccountService as;

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

}

这时虽然能保证事务的一致性,但是AccountServiceImpl的每个方法都变得十分繁琐、臃肿,为了单独处理事务控制,我们用动态代理。

代理模式

代理模式是一种结构型设计模式, 让你能够提供对象的替代品或其占位符。 代理控制着对于原对象的访问, 并允许在将请求提交给对象前后进行一些处理,如事务控制。

  • 为什么要控制对于某个对象的访问呢? 举个例子: 有这样一个消耗大量系统资源的巨型对象, 你只是偶尔需要使用它, 并非总是需要。
  • 你可以实现延迟初始化: 在实际有需要时再创建该对象。 对象的所有客户端都要执行延迟初始代码。 不幸的是, 这很可能会带来很多重复代码。
  • 在理想情况下, 我们希望将代码直接放入对象的类(上述业务层实现类)中, 但这并非总是能实现: 比如类可能是第三方封闭库的一部分。
    代理模式建议新建一个与原服务对象接口相同的代理类, 然后更新应用以将代理对象传递给所有原始对象客户端。 代理类接收到客户端请求后会创建实际的服务对象, 并将所有工作委派给它。
    这有什么好处呢? 如果需要在类的主要业务逻辑前后执行一些工作, 你无需修改类就能完成这项工作。 由于代理实现的接口与原类相同, 因此你可将其传递给任何一个使用实际服务对象的客户端。
    代理 (Proxy) 类包含一个指向服务对象的引用成员变量。 代理完成其任务 (例如延迟初始化、 记录日志、 访问控制和缓存等) 后会将请求传递给服务对象。 通常情况下, 代理会对其服务对象的整个生命周期进行管理。
    在这里插入图片描述

动态代理示例

对于销售产品,可以将经销商视为代理,经销商代理厂商销售产品,并且提供售后服务,但实际产品由厂商生产、售后服务也又厂商提供。

package com.ethan.proxy;

/**
 * @author Ethan
 * @date 2020/1/25 - 15:40
 * 对生产厂家要求的接口
 */
public interface Producer {

    void sellProduct(float money);

    void afterService(float money);
}

package com.ethan.proxy;

/**
 * @author Ethan
 * @date 2020/1/25 - 15:35
 */
public class ProducerImpl implements Producer {
    public void sellProduct(float money) {
        System.out.println("销售产品,并拿到钱:" + money);
    }

    public void afterService(float money) {
        System.out.println("提供售后服务,并拿到钱" + money);
    }
}

package com.ethan.proxy;

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

/**
 * @author Ethan
 * @date 2020/1/25 - 15:41
 * 模拟一个消费者
 */
public class Client {
    public static void main(String[] args) {
        final ProducerImpl producer = new ProducerImpl();
        /**
         * 动态代理:
         * 特点:字节码随用随创建,随用随加载
         * 作用:不修改源码的基础上对方法增强
         * 分类:基于接口的动态代理、基于子类的动态代理
         * 基于接口的动态代理:
         *      涉及的类:Proxy
         *      提供者:JDK官方
         *      创建方法:使用Proxy类中的newProxyInstance方法
         *      创建代理对象的要求:被代理类最少实现一个接口
         * newProxyInstance方法的参数:
         *      ClassLoader:类加载器
         *          它是用于加载代理对象字节码的。和被代理对象使用相同的类加载器。固定写法。
         *      Class[]:字节码数组
         *          它是用于让代理对象和被代理对象由相同方法
         *      InvocationHandler:用于提供增强的代码
         *          他是让我们写如何代理,我们一般都是写一个该接口的实现类,通常情况下都是匿名内部类,但不是必须的。
         *          此接口的实现类都是谁用谁写。
         */
        Producer proxyProducer = (Producer) Proxy.newProxyInstance(producer.getClass().getClassLoader(),
                producer.getClass().getInterfaces(),
                new InvocationHandler() {
                    /**
                     * 作用:执行被代理对象的任何接口方法都会经过该方法
                     * @param proxy     代理对象的引用
                     * @param method    当前执行的方法
                     * @param args      当前执行方法所需的参数
                     * @return          和被代理对象方法有相同的返回值
                     * @throws Throwable
                     */
                    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
                        //提供增强的代码
                        Object returnValue = null;
                        //1.获取方法执行的参数
                        Float money = (Float)args[0];
                        //判断当前方法是不是销售
                        if("sellProduct".equals(method.getName())) {
                            returnValue = method.invoke(producer, money * 0.8f);
                        }
                        return returnValue;
                    }
                });
        proxyProducer.sellProduct(10000f);
    }
}

这时用代理proxyProducer销售产品,同时可以让代理抽取提成,达到了代理的目的。

ServiceImpl的代理

为了代理ServiceImpl,我们设置一个工厂来返回业务层的代理。创建BeanFactory类如下:

在这里插入图片描述

package com.ethan.factory;

import com.ethan.domain.Account;
import com.ethan.service.AccountService;
import com.ethan.utils.TransactionManager;

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

/**
 * @author Ethan
 * @date 2020/1/25 - 18:21
 * 用于创建Service的代理对象的工厂
 */
public class BeanFactory {

    private AccountService accountService;

    private TransactionManager txManager;

    public void setTxManager(TransactionManager txManager) {
        this.txManager = txManager;
    }

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

    /**
     * 获取Service代理对象
     * @return
     */
    public AccountService getAccountService() {
        return (AccountService) Proxy.newProxyInstance(accountService.getClass().getClassLoader(), accountService.getClass().getInterfaces(),
                new InvocationHandler() {
                    /**
                     * 添加事务的支持
                     * @param proxy
                     * @param method
                     * @param args
                     * @return
                     * @throws Throwable
                     */
            public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
                Object rtValue = null;
                try {
                    txManager.beginTransaction();
                    rtValue = method.invoke(accountService, args);
                    txManager.commit();
                    return rtValue;
                } catch (Exception e) {
                    txManager.rollback();
                    throw new RuntimeException(e);
                } finally {
                    txManager.release();
                }
            }
        });
    }
}

这时我们将事务控制都移到了代理类中,AccountService就不用重复编写事务控制的语句了:

package com.ethan.service.impl;

import com.ethan.dao.AccountDAO;
import com.ethan.service.AccountService;
import com.ethan.domain.Account;
import com.ethan.utils.TransactionManager;

import java.util.List;

/**
 * @author Ethan
 * @date 2020/1/24 - 10:02
 */
public class AccountServiceImpl implements AccountService {

    private AccountDAO accountDAO;
    private TransactionManager txManager;

    public void setTxManager(TransactionManager txManager) {
        this.txManager = txManager;
    }

    public void setAccountDAO(AccountDAO accountDAO) {
        this.accountDAO = accountDAO;
    }

    public List<Account> findAllAccount() {
        return accountDAO.findAllAccount();
    }

    public Account findAccountById(Integer accountId) {
        return accountDAO.findAccountById(accountId);
    }

    public void saveAccount(Account account) {
        accountDAO.saveAccount(account);
    }

    public void updateAccount(Account account) {
        accountDAO.updateAccount(account);
    }

    public void deleteAccount(Integer accountId) {
        accountDAO.deleteAccount(accountId);
    }

    public void transfer(String sourceName, String targetName, Float money) {
        System.out.println("transferring...");
        Account source = accountDAO.findAccountByName(sourceName);
        Account target = accountDAO.findAccountByName(targetName);
        source.setMoney(source.getMoney() - money);
        target.setMoney(target.getMoney() + money);
        accountDAO.updateAccount(source);
        int a = 1 / 0;
        accountDAO.updateAccount(target);
    }
}

最后,我们要配置工厂类的代理对象,由于事务控制对象现在移到了代理类中,可以将ServiceImpl类中配置的TxManager去掉。同时要配置代理对象工厂AccountService对象和TransactionManager对象,配置如下:

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

    <!--配置beanfactory-->
    <bean id="beanFactory" class="com.ethan.factory.BeanFactory">
        <!--注入service-->
        <property name="accountService" ref="accountService"></property>
        <property name="txManager" ref="txManager"></property>
    </bean>

这时测试类应该调用代理的transfer方法,而不是直接调用AccountServiceImpl对象的transfer方法,故在测试类的AccountService对象上加上注解@Qualifier("proxyAccountService")

package com.ethan.test;

import com.ethan.service.AccountService;
import com.ethan.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;

/**
 * @author Ethan
 * @date 2020/1/24 - 10:37
 * 使用Junit单元测试:测试我们的配置
 */

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = "classpath:bean.xml")
public class AccountServiceTest {

    @Autowired
    @Qualifier("proxyAccountService")
    AccountService as;

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

至此,业务层实现类保持了它的简洁性和易读性,同时又运用代理实现了事务的一致性。

利用Spring的AOP控制事务(XML)

为了使用spring的AOP,先在pom文件导入AspectJ的坐标:

        <dependency>
            <groupId>org.aspectj</groupId>
            <artifactId>aspectjweaver</artifactId>
            <version>1.9.5</version>
        </dependency>

在bean.xml文件中加入aop名称空间:

       xmlns:aop="http://www.springframework.org/schema/aop"
    xsi:schemaLocation="http://www.springframework.org/schema/beans
        http://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/aop
        http://www.springframework.org/schema/aop/spring-aop.xsd">

这时的测试类:

package com.ethan.test;

import com.ethan.service.AccountService;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;

/**
 * @author Ethan
 * @date 2020/1/24 - 10:37
 * 使用Junit单元测试:测试我们的配置
 */

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = "classpath:bean.xml")
public class AccountServiceTest {

    @Autowired
    AccountService as;

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

只需在bean.xml文件中配置好切面:

    <aop:config>
        <aop:pointcut id="pt1" expression="execution(* com.ethan.service.impl.*.*(..))"/>
        <aop:aspect id="transactionControl" ref="txManager">
            <aop:before method="beginTransaction" pointcut-ref="pt1"></aop:before>
            <aop:after-returning method="commit" pointcut-ref="pt1"></aop:after-returning>
            <aop:after-throwing method="rollback" pointcut-ref="pt1"></aop:after-throwing>
            <aop:after method="release" pointcut-ref="pt1"></aop:after>
        </aop:aspect>
    </aop:config>

配置完成后的AccountServiceImpl的每项业务都是一个独立的事务,即保证了业务的一致性。

利用Spring的AOP控制事务(注解)

在bean.xml中配置以控制Spring扫描特定的包,并开启aspectJ的自动代理:

    <context:component-scan base-package="com.ethan"></context:component-scan>
    <aop:aspectj-autoproxy></aop:aspectj-autoproxy>

TransactionManager类上加上相应注解:

package com.ethan.utils;

import org.aspectj.lang.annotation.*;
import org.springframework.stereotype.Component;

import java.sql.SQLException;

/**
 * @author Ethan
 * @date 2020/1/25 - 11:16
 * 和事务管理相关的工具类,它包含了:开启事务、提交事务、回滚事务和释放连接
 */
@Component("txManager")
@Aspect
public class TransactionManager {

    private ConnectionUtils connectionUtils;

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

    @Pointcut("execution(* com.ethan.service.impl.*.*(..))")
    private void pt1() {}

    @Before("pt1()")
    public void beginTransaction() {
        try {
            connectionUtils.getThreadConnection().setAutoCommit(false);
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    @AfterReturning("pt1()")
    public void commit() {
        try {
            connectionUtils.getThreadConnection().commit();
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    @AfterThrowing("pt1()")
    public void rollback() {
        try {
            connectionUtils.getThreadConnection().rollback();
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    @After("pt1()")
    public void release() {
        try {
            connectionUtils.getThreadConnection().close();	//还回连接池中
            connectionUtils.removeConnection();
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
}

由于spring内部存在执行顺序的问题,注解并不能像XML配置一样保证事务的执行,以下方法改用环绕通知实现事务控制:

    @Around("pt1()")
    public Object aroundAdvice(ProceedingJoinPoint pjp) {
        Object rtValue = null;
        try {
            Object[] args = pjp.getArgs();
            this.beginTransaction();
            rtValue = pjp.proceed(args);
            this.commit();
            return rtValue;
        } catch (Throwable throwable) {
            throwable.printStackTrace();
            this.rollback();
            throw new RuntimeException();
        } finally {
            this.release();
        }
    }

这时就完成了利用Spring的AOP对事务进行控制。

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值