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

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

1.1 基于XML的AOP实现事务控制
1.打开IDEA界面如图所示,点击Create New Project。在这里插入图片描述
2.选择Maven工程和JDK的版本,点击Next。如图所示:在这里插入图片描述
3.填写项目的名称和保存的地址,点击Finish。如图所示:在这里插入图片描述
4.导入相应的依赖jar包的代码如下:

<?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.txw</groupId>
    <artifactId>day04__02account_aoptx_xml</artifactId>
    <version>1.0-SNAPSHOT</version>
    <!--打包的方式-->
    <packaging>jar</packaging>
    <dependencies>
        <!--导入spring的依赖jar包-->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context</artifactId>
            <version>5.2.7.RELEASE</version>
        </dependency>
        <!--导入spring整合junit的jar包-->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-test</artifactId>
            <version>5.2.6.RELEASE</version>
        </dependency>
        <!--导入dbutils的依赖jar包-->
        <dependency>
            <groupId>commons-dbutils</groupId>
            <artifactId>commons-dbutils</artifactId>
            <version>1.4</version>
        </dependency>
        <!--导入MySQL的依赖jar包-->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>5.1.6</version>
        </dependency>
        <!--导入c3p0的依赖jar包-->
        <dependency>
            <groupId>c3p0</groupId>
            <artifactId>c3p0</artifactId>
            <version>0.9.1.2</version>
        </dependency>
        <!--导入Junit单元测试的依赖jar包-->
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.13</version>
            <scope>test</scope>
        </dependency>
        <!--导入lombok的依赖jar包-->
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <version>1.18.12</version>
        </dependency>
        <dependency>
            <groupId>org.aspectj</groupId>
            <artifactId>aspectjweaver</artifactId>
            <version>1.9.5</version>
        </dependency>
    </dependencies>
</project>

5.创建账户的实体类的代码如下:

package com.txw.domain;

import lombok.Data;
import lombok.ToString;
import java.io.Serializable;
/**
 * 账户的实体类
 * @author adair
 */
@Data        // 自动生成set和get方法
@ToString      // 重写toString方法
@SuppressWarnings("all")         //  注解警告信息
public class Account implements Serializable {
    private Integer id;       // 账户的id
    private String name;      // 账户的名称
    private Float money;      // 账户的余额
}

6.创建账户的持久层接口的代码如下:

package com.txw.dao;

import com.txw.domain.Account;
import java.util.List;
/**
 * 账户的持久层接口
 * @author Adair
 */
@SuppressWarnings("all")         //  注解警告信息
public interface IAccountDao {
    /**
     * 查询所有
     * @return
     */
    List<Account> findAllAccount();
    /**
     * 根据id查询
     * @return
     */
    Account findAccountById(Integer accountId);
    /**
     * 保存账户
     * @param account
     */
    void saveAccount(Account account);
    /**
     * 更新账户
     * @param account
     */
    void updateAccount(Account account);
    /**
     * 删除账户
     * @param acccountId
     */
    void deleteAccount(Integer acccountId);
    /**
     * 根据名称查询账户
     * @param accountName
     * @return  如果有唯一的一个结果就返回,如果没有结果就返回null
     *          如果结果集超过一个就抛异常
     */
    Account findAccountByName(String accountName);
}

7.创建账户的持久层实现类的代码如下:

package com.txw.dao.impl;

import com.txw.dao.IAccountDao;
import com.txw.domain.Account;
import com.txw.utils.ConnectionUtils;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanHandler;
import org.apache.commons.dbutils.handlers.BeanListHandler;
import java.util.List;
/**
 * 账户的持久层实现类
 * @author Adair
 */
@SuppressWarnings("all")         //  注解警告信息
public class AccountDaoImpl implements IAccountDao {
    // 声明QueryRunner业务对象
    private QueryRunner runner;
    // 声明ConnectionUtils业务对象
    private ConnectionUtils connectionUtils;
    /**
     * set注入
     * @param runner
     */
    public void setRunner(QueryRunner runner) {
        this.runner = runner;
    }
    /**
     * set注入
     * @param connectionUtils
     */
    public void setConnectionUtils(ConnectionUtils connectionUtils) {
        this.connectionUtils = connectionUtils;
    }
    /**
     * 查询所有
     * @return
     */
    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查询
     * @param accountId
     * @return
     */
    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);
        }
    }
    /**
     * 保存账户
     * @param account
     */
    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);
        }
    }
    /**
     * 更新账户
     * @param account
     */
    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);
        }
    }
    /**
     * 更新账户
     * @param accountId
     */
    public void deleteAccount(Integer accountId) {
        try{
            runner.update(connectionUtils.getThreadConnection(),"delete from account where id=?",accountId);
        }catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
    /**
     * 根据名称查询账户
     * @param accountName
     * @return
     */
    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);
        }
    }
}

8.创建账户的业务层接口的代码如下:

package com.txw.service;

import com.txw.domain.Account;
import java.util.List;
/**
 * 账户的业务层接口
 * @author Adair
 */
@SuppressWarnings("all")         //  注解警告信息
public interface IAccountService {
    /**
     * 查询所有
     * @return
     */
    List<Account> findAllAccount();
        /**
     * 根据id查询
     * @return
     */
    Account findAccountById(Integer accountId);
    /**
     * 保存账户
     * @param account
     */
    void saveAccount(Account account);
    /**
     * 更新账户
     * @param account
     */
    void updateAccount(Account account);
    /**
     * 删除账户
     * @param acccountId
     */
    void deleteAccount(Integer acccountId);
    /**
     * 转账
     * @param sourceName        转出账户名称
     * @param targetName        转入账户名称
     * @param money             转账金额
     */
    void transfer(String sourceName,String targetName,Float money);
}

9.创建账户的业务层实现类的代码如下:

package com.txw.service.impl;

import com.txw.dao.IAccountDao;
import com.txw.domain.Account;
import com.txw.service.IAccountService;
import java.util.List;
/**
 * 账户的业务层实现类
 * 事务控制应该都是在业务层
 * @author Adair
 */
@SuppressWarnings("all")         // 注解警告信息
public class AccountServiceImpl implements IAccountService{
    // 声明IAccountDao业务对象
    private IAccountDao accountDao;
    /**
     * set注入
     * @param accountDao
     */
    public void setAccountDao(IAccountDao accountDao) {
        this.accountDao = accountDao;
    }
    /**
     * 查询所有
     * @return
     */
    public List<Account> findAllAccount() {
       return accountDao.findAllAccount();
    }
    /**
     * 根据id查询
     * @param accountId
     * @return
     */
    public Account findAccountById(Integer accountId) {
        return accountDao.findAccountById(accountId);
    }
    /**
     * 保存账户
     * @param account
     */
    public void saveAccount(Account account) {
        accountDao.saveAccount(account);
    }
    /**
     * 更新账户
     * @param account
     */
    public void updateAccount(Account account) {
        accountDao.updateAccount(account);
    }
    /**
     * 删除账户
     * @param acccountId
     */
    public void deleteAccount(Integer acccountId) {
        accountDao.deleteAccount(acccountId);
    }
    /**
     * 转账
     * @param sourceName        转出账户名称
     * @param targetName        转入账户名称
     * @param money             转账金额
     */
    public void transfer(String sourceName, String targetName, Float money) {
        System.out.println("transfer....");
            // 根据名称查询转出账户
            Account source = accountDao.findAccountByName(sourceName);
            // 根据名称查询转入账户
            Account target = accountDao.findAccountByName(targetName);
            // 转出账户减钱
            source.setMoney(source.getMoney()-money);
            // 转入账户加钱
            target.setMoney(target.getMoney()+money);
            // 更新转出账户
            accountDao.updateAccount(source);
//            int i=1/0;
            // 更新转入账户
            accountDao.updateAccount(target);
    }
}

10.创建连接的工具类的代码如下:

package com.txw.utils;

import javax.sql.DataSource;
import java.sql.Connection;
/**
 * 连接的工具类,它用于从数据源中获取一个连接,并且实现和线程的绑定
 * @author Adair
 */
@SuppressWarnings("all")         //  注解警告信息
public class ConnectionUtils {
    // 声明ThreadLocal业务对象
    private ThreadLocal<Connection> tl = new ThreadLocal<Connection>();
    // 声明DataSource业务对象
    private DataSource dataSource;
    /**
     * set注入
     * @param dataSource
     */
    public void setDataSource(DataSource dataSource) {
        this.dataSource = dataSource;
    }
    /**
     * 获取当前线程上的连接
     * @return
     */
    public Connection getThreadConnection() {
        try{
            // 先从ThreadLocal上获取
            Connection conn = tl.get();
            // 判断当前线程上是否有连接
            if (conn == null) {
                // 从数据源中获取一个连接,并且存入ThreadLocal中
                conn = dataSource.getConnection();
                tl.set(conn);
            }
            // 返回当前线程上的连接
            return conn;
        }catch (Exception e){
            throw new RuntimeException(e);
        }
    }
    /**
     * 把连接和线程解绑
     */
    public void removeConnection(){
        tl.remove();
    }
}

11.创建和事务管理相关的工具类代码如下:

package com.txw.utils;

/**
 * 和事务管理相关的工具类,它包含了,开启事务,提交事务,回滚事务和释放连接
 * @author Adair
 */
@SuppressWarnings("all")         //  注解警告信息
public class TransactionManager {
    // 声明ConnectionUtils业务对象
    private ConnectionUtils connectionUtils;
    /**
     * set注入
     * @param connectionUtils
     */
    public void setConnectionUtils(ConnectionUtils connectionUtils) {
        this.connectionUtils = connectionUtils;
    }
    /**
     * 开启事务
     */
    public  void beginTransaction(){
        try {
            connectionUtils.getThreadConnection().setAutoCommit(false);
        }catch (Exception e){
            e.printStackTrace();
        }
    }
    /**
     * 提交事务
     */
    public  void commit(){
        try {
            connectionUtils.getThreadConnection().commit();
        }catch (Exception e){
            e.printStackTrace();
        }
    }
    /**
     * 回滚事务
     */
    public  void rollback(){
        try {
            connectionUtils.getThreadConnection().rollback();
        }catch (Exception e){
            e.printStackTrace();
        }
    }
    /**
     * 释放连接
     */
    public  void release(){
        try {
            connectionUtils.getThreadConnection().close();//还回连接池中
            connectionUtils.removeConnection();
        }catch (Exception e){
            e.printStackTrace();
        }
    }
}

12.在resource创建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"
       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">
     <!-- 配置Service -->
    <bean id="accountService" class="com.txw.service.impl.AccountServiceImpl">
        <!-- 注入dao -->
        <property name="accountDao" ref="accountDao"></property>
    </bean>
    <!--配置Dao对象-->
    <bean id="accountDao" class="com.txw.dao.impl.AccountDaoImpl">
        <!-- 注入QueryRunner -->
        <property name="runner" ref="runner"></property>
        <!-- 注入ConnectionUtils -->
        <property name="connectionUtils" ref="connectionUtils"></property>
    </bean>
    <!--配置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"></property>
        <property name="user" value="root"></property>
        <property name="password" value="123456"></property>
    </bean>
    <!-- 配置Connection的工具类 ConnectionUtils -->
    <bean id="connectionUtils" class="com.txw.utils.ConnectionUtils">
        <!-- 注入数据源-->
        <property name="dataSource" ref="dataSource"></property>
    </bean>
    <!-- 配置事务管理器-->
    <bean id="txManager" class="com.txw.utils.TransactionManager">
        <!-- 注入ConnectionUtils -->
        <property name="connectionUtils" ref="connectionUtils"></property>
    </bean>
    <!--配置aop-->
    <aop:config>
        <!--配置通用切入点表达式-->
        <aop:pointcut id="pt1" expression="execution(* com.txw.service.impl.*.*(..))"></aop:pointcut>
        <aop:aspect id="txAdvice" 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>
</beans>

13.测试类的代码如下:

package com.txw.test;

import com.txw.service.IAccountService;
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;
/**
 * 使用Junit单元测试:测试我们的配置
 * @author Adair
 */
@SuppressWarnings("all")         //  注解警告信息
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = "classpath:bean.xml")
public class AccountServiceTest {
    // 声明IAccountService业务对象
    @Autowired
    private  IAccountService as;
    @Test
    public  void testTransfer(){
        as.transfer("aaa","bbb",100f);
    }
}

运行之前的数据库的数据如图所示:在这里插入图片描述
运行测试代码如图所示:在这里插入图片描述
运行之后的数据库的数据如图所示:说明控制住事务!在这里插入图片描述

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
Spring AOP(面向切面编程)是Spring框架的一个重要特性,它允许开发者在程序运行时动态地将额外的行为织入到现有的代码,而不需要修改原始代码。其事务控制Spring AOP的一个常见应用场景。 在Spring事务控制是通过AOP实现的。通过配置AOP,我们可以将事务相关的代码(如开启事务、提交事务、回滚事务等)织入到业务方法的执行过程。这样,我们就可以将事务的管理与业务逻辑解耦,提高代码的可维护性和可重用性。 在进行Spring AOP配置时,我们通常需要以下几个步骤: 1. 引入AOP依赖:在项目的依赖管理文件(如pom.xml添加相关的AOP依赖,如spring-aopspring-context等。 2. 配置AOP代理:在Spring配置文件(如applicationContext.xml配置AOP代理,通常使用<aop:config>元素进行配置。在配置,我们可以指定要代理的目标对象和切面类,以及切面类定义的通知(如@Before、@After、@Around等)。 3. 配置事务管理器:在Spring配置文件配置事务管理器,通常使用<tx:annotation-driven>元素进行配置。在配置,我们可以指定事务管理器的类型(如基于JDBC的事务管理器或基于JTA的事务管理器)。 4. 配置事务切面:在切面类,我们可以使用@Transactional注解来标记需要进行事务管理的方法或类。通过这些注解,Spring会在方法执行前后自动开启、提交或回滚事务。 总结来说,Spring AOP配置的核心就是定义切面类和通知,并通过AOP代理将其织入到目标对象的方法执行过程。对于事务控制,我们可以利用@Transactional注解来定义需要进行事务管理的方法或类。这样,Spring会根据配置自动管理事务的开启、提交和回滚操作,简化了事务管理的代码编写。

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

学无止路

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值