Spring中基于注解的AOP实现事务控制

数据库表
在这里插入图片描述
IDEA中创建maven项目

整体构架

在这里插入图片描述

pom.xml

<?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.uek</groupId>
    <artifactId>spring04-study04-account-AOP-annotation-Transfer</artifactId>
    <version>1.0-SNAPSHOT</version>

    <packaging>jar</packaging>

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

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

        <!--spring整合junit的jar-->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-test</artifactId>
            <version>5.0.2.RELEASE</version>
        </dependency>

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

        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>5.1.6</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.12</version>
        </dependency>
    </dependencies>

</project>

entity

/**
 * 账户的实体类
 */
public class Account implements Serializable {

    private Integer id;
    private String name;
    private Float money;

    public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public Float getMoney() {
        return money;
    }

    public void setMoney(Float money) {
        this.money = money;
    }

    @Override
    public String toString() {
        return "Account{" +
                "id=" + id +
                ", name='" + name + '\'' +
                ", money=" + money +
                '}';
    }
}

dao

/**
 * 账户的持久层接口
 */
public interface IAccountDao {

    //查询所有
    List<Account> findAllAccount() throws SQLException;

    //根据id查询
    Account findAccountById(Integer accountId);

    //插入
    void saveAccount(Account account);

    //更新
    void updateAccount(Account account);

    //删除
    void deleteAccount(Integer accountId);

    /**
     * 根据名称查询账户
     * @param accountName
     * @return  如果有唯一的一个结果就返回,如果没有结果就返回null
     *          如果结果集超过一个就抛异常
     */
    Account findAccountByName(String accountName);

}

/**
 * 账户的持久层实现类
 */
@Repository("accountDao")
public class AccountDaoImpl implements IAccountDao {

    @Autowired
    private QueryRunner runner;

    @Autowired
    private ConnectionUtils connectionUtils;


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

    }

    //根据id查询
    public Account findAccountById(Integer accountId) {
        try {
            return runner.query(connectionUtils.getThreadConnection(),"select * from account where id = ? ",new BeanHandler<Account>(Account.class),accountId);
        }catch (Exception 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 (Exception 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 (Exception e){
            throw new RuntimeException(e);
        }
    }

    //删除
    public void deleteAccount(Integer accountId) {
        try {
            runner.update(connectionUtils.getThreadConnection(),"delete from account where id =?",accountId);
        }catch (Exception 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 (Exception e){
            throw new RuntimeException(e);
        }
    }
}

service

/**
 * 账户的业务层接口
 */
public interface IAccountService {

    //查询所有
    List<Account> findAllAccount() throws SQLException;

    //根据id查询
    Account findAccountById(Integer accountId) throws SQLException;

    //插入
    void saveAccount(Account account) throws SQLException;

    //更新
    void updateAccount(Account account) throws SQLException;

    //删除
    void deleteAccount(Integer accountId) throws SQLException;

    /**
     * 转账
     * @param sourceName   转出账户名称
     * @param targetName   转入账户名称
     * @param money        转账金额
     */
    void transfer(String sourceName,String targetName,Float money) throws SQLException;


}

/**
 * 账户的业务层实现类
 * 事务的控制应该都是在业务层的
 */
@Service("accountService")
public class AccountServiceImpl implements IAccountService {

    @Autowired
    private IAccountDao accountDao;

    //查询所有
    public List<Account> findAllAccount() throws SQLException {
        return accountDao.findAllAccount();
    }

    //根据id查询
    public Account findAccountById(Integer accountId) throws SQLException {
        return accountDao.findAccountById(accountId);
    }

    //插入
    public void saveAccount(Account account) throws SQLException {
        accountDao.saveAccount(account);
    }

    //更新
    public void updateAccount(Account account) throws SQLException {
        accountDao.updateAccount(account);
    }

    //删除
    public void deleteAccount(Integer accountId) throws SQLException {
       accountDao.deleteAccount(accountId);
    }

    //转账
    public void transfer(String sourceName, String targetName, Float money) throws SQLException {
        System.out.println("transfer开始执行.......");
        //1).根据名称查询转出账户
        Account source = accountDao.findAccountByName(sourceName);
        //2).根据名称查询转入账户
        Account target = accountDao.findAccountByName(targetName);
        //3).转出账户减钱
        source.setMoney(source.getMoney() - money);
        //4).转入账户加钱
        target.setMoney(target.getMoney() + money);
        //5).更新转出账户
        accountDao.updateAccount(source);

      //  int i = 1/0;

        //6).更新转入账户
        accountDao.updateAccount(target);
    }
}

utils


/**
 * 连接的工具类,它用于从数据源中获取一个连接,并且实现和线程的绑定
 */
@Component("connectionUtils")
public class ConnectionUtils {

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

    @Autowired
    private DataSource dataSource;

    public void setTl(ThreadLocal<Connection> tl) {
        this.tl = tl;
    }

    //获取当前线程上的连接
    public Connection getThreadConnection() throws SQLException {
        //1.先从ThreadLocal上获取
        Connection conn = tl.get();
        //2.判断当前线程上是否有连接
        if(conn == null){
            //3.从数据源中获取一个连接,并且存入ThreadLocal中
            conn = dataSource.getConnection();
            tl.set(conn);
        }
        //4.返回当前线程上的连接
        return conn;
    }

    //把连接和线程解绑
    public void removeConnection(){
        tl.remove();
    }


}

/**
 * 和事务管理相关的工具类,它包含了开启事务,提交事务,回滚事务和释放连接
 */
@Component("txManager")
@Aspect
public class TransactionManager {

    //获取当前线程的Connection
    @Autowired
    private ConnectionUtils connectionUtils;

    @Pointcut("execution(* com.uek.service.impl.*.*(..))")
    public void pt(){}

    //开启事务
    public void beginTransaction() throws SQLException {
        connectionUtils.getThreadConnection().setAutoCommit(false);
    }

    //提交事务
    public void commit() throws SQLException {
        connectionUtils.getThreadConnection().commit();
    }

    //回滚事务
    public void rollback() throws SQLException {
        connectionUtils.getThreadConnection().rollback();
    }

    //释放连接
    public void release() throws SQLException {
        //还回连接池
        connectionUtils.getThreadConnection().close();
        connectionUtils.removeConnection();
    }

    @Around("pt()")
    public Object aroundAdvice(ProceedingJoinPoint pjp) throws SQLException {
        Object rtValue = null;
        try {
            //1.获取参数
            Object[] args = pjp.getArgs();
            //2.开启事务
            this.beginTransaction();
            //3.执行方法
            rtValue = pjp.proceed(args);
            //4.提交事务
            this.commit();

            //返回结果
            return rtValue;
        }catch (Throwable t){
            //5.回滚事务
            this.rollback();
            throw new RuntimeException(t);
        }finally {
            //6.释放资源
            this.release();

        }
    }
}

bean.xml

<?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:aop="http://www.springframework.org/schema/aop"
       xmlns:context="http://www.springframework.org/schema/context"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
        https://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/aop
        https://www.springframework.org/schema/aop/spring-aop.xsd
        http://www.springframework.org/schema/context
        https://www.springframework.org/schema/context/spring-context.xsd">

    <!--配置spring创建容器时要扫描的包-->
    <context:component-scan base-package="com.uek"></context:component-scan>



    <!--配置QueryRunner对象-->
    <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.jdbc.Driver"></property>
        <property name="jdbcUrl" value="jdbc:mysql://localhost:3306/spring?useUnicode=true&amp;characterEncoding=utf-8&amp;useSSL=false"></property>
        <property name="user" value="root"></property>
        <property name="password" value="root"></property>
    </bean>

    <!--开启spring对注解AOP的支持-->
    <aop:aspectj-autoproxy></aop:aspectj-autoproxy>
</beans>

测试类

/**
 * 使用Junit单元测试
 */
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = "classpath:bean.xml")
public class AccountServiceTest {

    @Autowired
    private IAccountService ias;

    //测试转账
    @Test
    public void testTransfer() throws SQLException {
        ias.transfer("aaa","bbb",100f);
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值