spring事务理解

本文探讨了Spring事务的两种使用方式:通过@Transaction注解和使用事务模板。详细解读了Spring如何通过AOP拦截事务注解方法,解析事务属性,并在特定条件下创建新事务。核心代码涉及TransactionAspectSupport和DataSourceUtils类,特别是getConnection方法,它是获取带事务数据库连接的关键,无论使用MyBatis、JdbcTemplate还是Hibernate,都会依赖此方法。
摘要由CSDN通过智能技术生成

spring事务使用方式:

1、通过注解的方式:@Transactional

在需要配置数据库事务的方法上加上上面的注解即可使用spring事务

2、使用事务模板代码创建事务

源码解读:

比如在使用@Transactional注解时候,spring框架通过aop的方式拦截带有@Transactional注解的方法,解析@Transactional注解里面配置的事务传播方式、事务隔离级别等信息

源码实现:org.springframework.transaction.interceptor.TransactionAspectSupport#invokeWithinTransaction

protected Object invokeWithinTransaction(Method method, Class<?> targetClass, final InvocationCallback invocation)
			throws Throwable {

		// If the transaction attribute is null, the method is non-transactional.
		final TransactionAttribute txAttr = getTransactionAttributeSource().getTransactionAttribute(method, targetClass);
		final PlatformTransactionManager tm = determineTransactionManager(txAttr);
		final String joinpointIdentification = methodIdentification(method, targetClass, txAttr);

		if (txAttr == null || !(tm instanceof CallbackPreferringPlatformTransactionManager)) {
			// Standard transaction demarcation with getTransaction and commit/rollback calls.
            //如有必要则创建事务
			TransactionInfo txInfo = createTransactionIfNecessary(tm, txAttr, joinpointIdentification); 
			Object retVal = null;
			try {
				// This is an around advice: Invoke the next interceptor in the chain.
				// This will normally result in a target object being invoked.
				retVal = invocation.proceedWithInvocation();
			}
			catch (Throwable ex) {
				// target invocation exception
				completeTransactionAfterThrowing(txInfo, ex);
				throw ex;
			}
			finally {
				cleanupTransactionInfo(txInfo);
			}
			commitTransactionAfterReturning(txInfo);
			return retVal;
		}

		
	}

在上面代码中有这样一个方法调用:

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值