spring事务管理@Transactional 解析spring事务管理@Transactional为什么要添加rollbackFor=Exception.class

软件发布|下载排行|最新软件

当前位置:首页IT学院IT技术

spring事务管理@Transactional 解析spring事务管理@Transactional为什么要添加rollbackFor=Exception.class

卖柴火的小伙子   2021-11-15 我要评论
想了解解析spring事务管理@Transactional为什么要添加rollbackFor=Exception.class的相关内容吗,卖柴火的小伙子在本文为您仔细讲解spring事务管理@Transactional的相关知识和一些Code实例,欢迎阅读和指正,我们先划重点:spring事务管理@Transactional,spring事务,下面大家一起来学习吧。

spring中事务处理原理

    利用aop生成代理对象执行带有Transactional事务注解的方法业务逻辑.项目启动过程中会生成代理对象并将Transactional注解中的属性进行解析加载处理.在方法执行过程中如果出现异常,会根据注解配置决定是进入到事务回滚处理还是事务提交处理逻辑中,事务回滚处理逻辑中最终还是基于数据库的事务回滚处理.

异常的分类

在这里插入图片描述

案例说明

    以自定义异常为例说明一下@Transactional中是否指定rollbackFor=Exception.class的区别
    未指定rollbackFor属性

  	 @Transactional
    @GetMapping("/addSysMenu")
    public void addSysMenu() throws Exception {
    	// 更新菜单名称(将id为1的菜单名修改为系统管理测试)
        int k = sysMenuDao.updateSysMenu(1, "系统管理测试");
        System.out.println(k);
        // 自定义异常,抛出非运行期异常
        throw new Exception("自定义异常");
        // 执行结果:程序终止,数据库中菜单id为1的菜单名修改成功.说明事物没有回滚.
    }

    指定rollbackFor属性

    @Transactional(rollbackFor = Exception.class)
    @GetMapping("/addSysMenu")
    public void addSysMenu(String menuName) throws Exception {
   		 // 更新菜单名称(将id为1的菜单名修改为系统管理测试)
        int k = sysMenuDao.updateSysMenu(1, "系统管理测试");
        System.out.println(k);
        // 自定义异常,抛出非运行期异常
        throw new Exception("自定义异常");
         // 执行结果:程序终止,数据库中菜单id为1的菜单名没有修改.说明事物回滚.
    }

原因分析

    其他帖子都说如果不加的话仅支持运行期异常以及error错误类型.对于非运行期异常是不支持的.这里提供一下这种说法的来源.
先看一下@Transactional注解中关于rollbackFor的使用说明

@Target({ElementType.TYPE, ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
@Inherited
@Documented
public @interface Transactional {
	// 省略部分代码............
	// By default, a transaction will be rolling back on {@link RuntimeException} and {@link Error} but not on checked exceptions (business exceptions).
	// 翻译:指定事物回滚的异常类型,默认仅对于运行期异常和错误支持事务回滚,对于检查异常(业务异常是不支持的)
	Class<? extends Throwable>[] rollbackFor() default {};
	}

    至于加上@Transactional中指定rollbackFor=Exception.class以后是如何起作用的接着往下看.
spring中事务回滚的大概逻辑是,发生异常之后,会根据配置的事务属性判断是否进行回滚的处理,如果不进行事务回滚则直接进行事务提交.这里重要的体现是在:TransactionAspectSupport.java中completeTransactionAfterThrowing

// 发生异常时事务处理方式
protected void completeTransactionAfterThrowing(@Nullable TransactionInfo txInfo, Throwable ex) {
		if (txInfo != null && txInfo.getTransactionStatus() != null) {
			// 省略部分代码.......
			// 判断异常是否为运行期异常或是error,如果是则执行回滚处理,如果不是则提交事务
			if (txInfo.transactionAttribute != null && txInfo.transactionAttribute.rollbackOn(ex)) {
					// 回滚事务处理
					txInfo.getTransactionManager().rollback(txInfo.getTransactionStatus());
					// 省略部分代码......
			}
			else {
					// 提交事务
					txInfo.getTransactionManager().commit(txInfo.getTransactionStatus());
					// 省略部分代码.......
			}
		}
	}

    而判断事务是否支持回滚的处理在RuleBasedTransactionAttribute.java中transactionAttribute.rollbackOn()

// 判断异常是否支持事务回滚处理
public boolean rollbackOn(Throwable ex) {
	
		RollbackRuleAttribute winner = null;
		// 省略部分代码....................
		// winner 是判断@Transactional中是否有rollBackFor属性,如果没有则说明没有指定,按照默认的方式进行判断(DefaultTransactionAttribute.java中rollbackOn),如果有则只判断是否属于NoRollbackRuleAttribute类型,如果不是则说明支持事务回滚.关于变量win对应的RollbackRuleAttribute如何进行的赋值下面继续.
		if (winner == null) {
			return super.rollbackOn(ex);
		}
		return !(winner instanceof NoRollbackRuleAttribute);
	}

    DefaultTransactionAttribute.java中rollbackOn,是否支持事务回滚的默认判断方式:是否是运行期异常或是是否是错误类型(与Transactional注解中的rollbackFor属性说明相对应).

public boolean rollbackOn(Throwable ex) {
		return (ex instanceof RuntimeException || ex instanceof Error);
	}

    RollbackRuleAttribute中如何进行的赋值问题,具体来讲是项目启动之后会扫描带有Transactional注解的方法,然后将注解中标注的属性获取之后进行参数配置.具体体现是在:SpringTransactionAnnotationParser.java中parseTransactionAnnotation

protected TransactionAttribute parseTransactionAnnotation(AnnotationAttributes attributes) {
		RuleBasedTransactionAttribute rbta = new RuleBasedTransactionAttribute();
		// 省略部分代码.........
		// 获取注解上的rollbackFor属性值
		List<RollbackRuleAttribute> rollbackRules = new ArrayList<>();
		for (Class<?> rbRule : attributes.getClassArray("rollbackFor")) {
			rollbackRules.add(new RollbackRuleAttribute(rbRule));
		}
		// 省略部分代码.........

		return rbta;
	}

    至此关于为什么@Transactional为什么要添加rollbackFor=Exception.class原因以讲述完毕!

Copyright 2022 版权所有 软件发布 访问手机版

声明:所有软件和文章来自软件开发商或者作者 如有异议 请与本站联系 联系我们