Spring5源码(40)-基于tx标签和基于@Transactional注解的声明式事物介绍

本文涉及的产品
RDS MySQL Serverless 基础系列,0.5-2RCU 50GB
RDS MySQL Serverless 高可用系列,价值2615元额度,1个月
简介: Spring5源码(40)-基于tx标签和基于@Transactional注解的声明式事物介绍


上一节中已经对Spring事物的一些基本概念和核心接口做了简介,并且演示了编程式事物实现,接下来介绍Spring中的另一种事物管理实现--声明式事物

其底层建立在 AOP 的基础之上,对方法前后进行拦截,然后在目标方法开始之前创建或者加入一个事务,在执行完目标方法之后根据执行情况提交或者回滚事务。通过声明式事物,无需在业务逻辑代码中掺杂事务管理的代码,只需在配置文件中做相关的事务规则声明(或通过等价的基于标注的方式),便可以将事务规则应用到业务逻辑中。

声明式事物的实现方式有很多种,例如基于TransactionInterceptor、TransactionProxyFactoryBean、tx标签、Transactional注解等等。下面我们演示一下tx标签和Transactional的使用,为接下来的源码分析做好准备。

1.基于tx标签的声明式事物
  • bean

package com.lyc.cn.v2.day08;
/**
 * 账户接口
 * @author: LiYanChao
 * @create: 2018-11-07 18:38
 */
public interface AccountServiceImp {
    void save() throws RuntimeException;
}

package com.lyc.cn.v2.day08;
import org.springframework.jdbc.core.JdbcTemplate;
/**
 * 账户接口实现
 * @author: LiYanChao
 * @create: 2018-11-07 18:39
 */
public class AccountServiceImpl implements AccountServiceImp {
    private JdbcTemplate jdbcTemplate;
    private static String insert_sql = "insert into account(balance) values (100)";
    @Override
    public void save() throws RuntimeException {
        System.out.println("==开始执行sql");
        jdbcTemplate.update(insert_sql);
        System.out.println("==结束执行sql");
        System.out.println("==准备抛出异常");
        throw new RuntimeException("==手动抛出一个异常");
    }
    public void setJdbcTemplate(JdbcTemplate jdbcTemplate) {
        this.jdbcTemplate = jdbcTemplate;
    }
}
  • 配置文件

<?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:tx="http://www.springframework.org/schema/tx"
       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/tx
        http://www.springframework.org/schema/tx/spring-tx.xsd
        http://www.springframework.org/schema/aop
        http://www.springframework.org/schema/aop/spring-aop.xsd">
    <!--事物管理器-->
    <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
        <property name="dataSource" ref="dataSource"/>
    </bean>
    <!--数据源-->
    <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource">
        <property name="driverClassName" value="com.mysql.jdbc.Driver"/>
        <property name="url" value="jdbc:mysql://localhost:3306/my_test?useSSL=false&amp;useUnicode=true&amp;characterEncoding=UTF-8"/>
        <property name="username" value="root"/>
        <property name="password" value="liyanchao1989@"/>
    </bean>
    <!--jdbcTemplate-->
    <bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
        <property name="dataSource" ref="dataSource"/>
    </bean>
    <!--业务bean-->
    <bean id="accountService" class="com.lyc.cn.v2.day08.AccountServiceImpl">
        <property name="jdbcTemplate" ref="jdbcTemplate"/>
    </bean>
    <!--tx标签配置-->
    <tx:advice id="txAdvice" transaction-manager="transactionManager">
        <tx:attributes>
            <tx:method name="save*" propagation="REQUIRED"/>
            <tx:method name="delete*" propagation="REQUIRED"/>
            <tx:method name="update*" propagation="REQUIRED"/>
            <tx:method name="query*" propagation="REQUIRED"/>
            <tx:method name="*" read-only="true"/>
        </tx:attributes>
    </tx:advice>
    <!--aop配置-->
    <aop:config>
        <aop:pointcut id="txPointcut" expression="execution(* com.lyc.cn.v2.day08..*.*(..))"/>
        <aop:advisor advice-ref="txAdvice" pointcut-ref="txPointcut"/>
    </aop:config>
</beans>
  • 测试类及结果

@Test
public void test2() {
    // 基于tx标签的声明式事物
    ApplicationContext ctx = new ClassPathXmlApplicationContext("v2/day08.xml");
    AccountServiceImp studentService = ctx.getBean("accountService", AccountServiceImp.class);
    studentService.save();
}

==开始执行sql
==结束执行sql
==准备抛出异常
java.lang.RuntimeException: ==手动抛出一个异常
    at com.lyc.cn.v2.day08.AccountServiceImpl.save(AccountServiceImpl.java:24)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)

测试方法中手动抛出了一个异常,Spring会自动回滚事物,查看数据库可以看到并没有新增记录。

2.基于@Transactional注解的声明式事物
  • bean

package com.lyc.cn.v2.day09;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
/**
 * 账户接口
 * @author: LiYanChao
 * @create: 2018-11-07 18:38
 */
@Transactional(propagation = Propagation.REQUIRED)
public interface AccountServiceImp {
    void save() throws RuntimeException;
}

package com.lyc.cn.v2.day09;
import org.springframework.jdbc.core.JdbcTemplate;
/**
 * 账户接口实现
 * @author: LiYanChao
 * @create: 2018-11-07 18:39
 */
public class AccountServiceImpl implements AccountServiceImp {
    private JdbcTemplate jdbcTemplate;
    private static String insert_sql = "insert into account(balance) values (100)";
    @Override
    public void save() throws RuntimeException {
        System.out.println("==开始执行sql");
        jdbcTemplate.update(insert_sql);
        System.out.println("==结束执行sql");
        System.out.println("==准备抛出异常");
        throw new RuntimeException("==手动抛出一个异常");
    }
    public void setJdbcTemplate(JdbcTemplate jdbcTemplate) {
        this.jdbcTemplate = jdbcTemplate;
    }
}
  • 配置文件

<?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:tx="http://www.springframework.org/schema/tx"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
        http://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/tx
        http://www.springframework.org/schema/tx/spring-tx.xsd">
    <!--开启tx注解-->
    <tx:annotation-driven transaction-manager="transactionManager"/>
    <!--事物管理器-->
    <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
        <property name="dataSource" ref="dataSource"/>
    </bean>
    <!--数据源-->
    <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource">
        <property name="driverClassName" value="com.mysql.jdbc.Driver"/>
        <property name="url" value="jdbc:mysql://localhost:3306/my_test?useSSL=false&amp;useUnicode=true&amp;characterEncoding=UTF-8"/>
        <property name="username" value="root"/>
        <property name="password" value="liyanchao1989@"/>
    </bean>
    <!--jdbcTemplate-->
    <bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
        <property name="dataSource" ref="dataSource"/>
    </bean>
    <!--业务bean-->
    <bean id="accountService" class="com.lyc.cn.v2.day09.AccountServiceImpl">
        <property name="jdbcTemplate" ref="jdbcTemplate"/>
    </bean>
</beans>
  • 测试及结果

package com.lyc.cn.v2.day09;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
/**
 * @author: LiYanChao
 * @create: 2018-11-07 18:45
 */
public class MyTest {
    @Test
    public void test1() {
        // 基于tx标签的声明式事物
        ApplicationContext ctx = new ClassPathXmlApplicationContext("v2/day09.xml");
        AccountServiceImp studentService = ctx.getBean("accountService", AccountServiceImp.class);
        studentService.save();
    }
}

==开始执行sql
==结束执行sql
==准备抛出异常
java.lang.RuntimeException: ==手动抛出一个异常
    at com.lyc.cn.v2.day09.AccountServiceImpl.save(AccountServiceImpl.java:24)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)

测试方法中手动抛出了一个异常,Spring会自动回滚事物,查看数据库可以看到并没有新增记录。

3.总结

以上两种方式都比较简单,只要配置正确就可以,当然很多细节并没有分析到,感兴趣的同学可以参考Spring的官方文档查看更多的细节化的配置,接下来我们就分析基于@Transactional注解的声明式事物的的源码实现。



相关实践学习
基于CentOS快速搭建LAMP环境
本教程介绍如何搭建LAMP环境,其中LAMP分别代表Linux、Apache、MySQL和PHP。
全面了解阿里云能为你做什么
阿里云在全球各地部署高效节能的绿色数据中心,利用清洁计算为万物互联的新世界提供源源不断的能源动力,目前开服的区域包括中国(华北、华东、华南、香港)、新加坡、美国(美东、美西)、欧洲、中东、澳大利亚、日本。目前阿里云的产品涵盖弹性计算、数据库、存储与CDN、分析与搜索、云通信、网络、管理与监控、应用服务、互联网中间件、移动服务、视频服务等。通过本课程,来了解阿里云能够为你的业务带来哪些帮助 &nbsp; &nbsp; 相关的阿里云产品:云服务器ECS 云服务器 ECS(Elastic Compute Service)是一种弹性可伸缩的计算服务,助您降低 IT 成本,提升运维效率,使您更专注于核心业务创新。产品详情: https://www.aliyun.com/product/ecs
目录
相关文章
|
1天前
|
小程序 JavaScript Java
小程序商城|基于Spring Boot的智能小程序商城的设计与实现(源码+数据库+文档)
小程序商城|基于Spring Boot的智能小程序商城的设计与实现(源码+数据库+文档)
7 0
小程序商城|基于Spring Boot的智能小程序商城的设计与实现(源码+数据库+文档)
|
1天前
|
小程序 JavaScript Java
高校宿舍信息|基于Spring Boot的高校宿舍信息管理系统的设计与实现(源码+数据库+文档)
高校宿舍信息|基于Spring Boot的高校宿舍信息管理系统的设计与实现(源码+数据库+文档)
6 0
|
1天前
|
安全 JavaScript Java
在线问卷调查|基于Spring Boot的在线问卷调查系统的设计与实现(源码+数据库+文档)
在线问卷调查|基于Spring Boot的在线问卷调查系统的设计与实现(源码+数据库+文档)
6 0
|
8天前
|
Java 关系型数据库 MySQL
【JavaEE】Spring事务-@Transactional参数介绍-事务的隔离级别以及传播机制
【JavaEE】Spring事务-@Transactional参数介绍-事务的隔离级别以及传播机制
12 0
|
8天前
|
消息中间件 Java 关系型数据库
【JavaEE】Spring事务-事务的基本介绍-事务的实现-@Transactional基本介绍和使用
【JavaEE】Spring事务-事务的基本介绍-事务的实现-@Transactional基本介绍和使用
19 0
|
8天前
|
XML Java uml
spring 源码解析——第一篇(ioc xml方式)
spring 源码解析——第一篇(ioc xml方式)
35 0
|
8天前
|
安全 Java 应用服务中间件
阿里技术官架构使用总结:Spring+MyBatis源码+Tomcat架构解析等
分享Java技术文以及学习经验也有一段时间了,实际上作为程序员,我们都清楚学习的重要性,毕竟时代在发展,互联网之下,稍有一些落后可能就会被淘汰掉,因此我们需要不断去审视自己,通过学习来让自己得到相应的提升。
|
7月前
|
Java 应用服务中间件 Spring
66Spring - 源码解析Spring的启动机制(contextConfigLocation)
66Spring - 源码解析Spring的启动机制(contextConfigLocation)
45 0
|
8天前
|
Java 关系型数据库 数据库连接
Spring源码解析--深入Spring事务原理
本文将带领大家领略Spring事务的风采,Spring事务是我们在日常开发中经常会遇到的,也是各种大小面试中的高频题,希望通过本文,能让大家对Spring事务有个深入的了解,无论开发还是面试,都不会让Spring事务成为拦路虎。
42 1
|
8天前
|
XML 人工智能 Java
Spring Bean名称生成规则(含源码解析、自定义Spring Bean名称方式)
Spring Bean名称生成规则(含源码解析、自定义Spring Bean名称方式)