05.Spring Framework 源码解析之事务

本文详细解析了Spring框架中事务管理的实现原理,包括环境搭建、源码分析、组件导入及核心代码剖析。重点介绍了@EnableTransactionManagement的作用,以及TransactionInterceptor如何进行事务拦截。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1. 环境搭建

代码已经上传至 https://github.com/masteryourself/spring-framework,工程是 tutorial-spring-tx

2. 源码解析

详细的源码注释可参考 https://github.com/masteryourself/spring-framework

2.1 组件导入
2.1.1 流程分析

@EnableTransactionManagement

@EnableTransactionManagement 给容器中导入了 TransactionManagementConfigurationSelector 组件,这个组件会导入 AutoProxyRegistrarProxyTransactionManagementConfiguration

其中 AutoProxyRegistrar 会判断是否需要给容器中导入 InfrastructureAdvisorAutoProxyCreator 组件(只要容器中没有叫 org.springframework.aop.config.internalAutoProxyCreator 的组件就会自动导入)

InfrastructureAdvisorAutoProxyCreator

InfrastructureAdvisorAutoProxyCreator 关系图如上,它实现了 SmartInstantiationAwareBeanPostProcessor 接口,和前文 AOP 源码解析分析基本相同,由此可见它也是向容器中导入创建代理的组件

2.1.2 核心代码剖析
1. ProxyTransactionManagementConfiguration
  • 它会给容器自动导入 3 个用于事务场景的组件
@Configuration
public class ProxyTransactionManagementConfiguration extends AbstractTransactionManagementConfiguration {

	/**
	 * 给容器中导入事务增强器组件
	 * @return {@link BeanFactoryTransactionAttributeSourceAdvisor}
	 */
	@Bean(name = TransactionManagementConfigUtils.TRANSACTION_ADVISOR_BEAN_NAME)
	@Role(BeanDefinition.ROLE_INFRASTRUCTURE)
	public BeanFactoryTransactionAttributeSourceAdvisor transactionAdvisor() {
		BeanFactoryTransactionAttributeSourceAdvisor advisor = new BeanFactoryTransactionAttributeSourceAdvisor();
		advisor.setTransactionAttributeSource(transactionAttributeSource());
		advisor.setAdvice(transactionInterceptor());
		if (this.enableTx != null) {
			advisor.setOrder(this.enableTx.<Integer>getNumber("order"));
		}
		return advisor;
	}

	/**
	 * 给容器中导入事务属性解析组件
	 * @return {@link TransactionAttributeSource}
	 */
	@Bean
	@Role(BeanDefinition.ROLE_INFRASTRUCTURE)
	public TransactionAttributeSource transactionAttributeSource() {
		return new AnnotationTransactionAttributeSource();
	}

	/**
	 * 给容器中导入事务拦截器
	 * @return {@link TransactionInterceptor}
	 */
	@Bean
	@Role(BeanDefinition.ROLE_INFRASTRUCTURE)
	public TransactionInterceptor transactionInterceptor() {
		TransactionInterceptor interceptor = new TransactionInterceptor();
		interceptor.setTransactionAttributeSource(transactionAttributeSource());
		if (this.txManager != null) {
			interceptor.setTransactionManager(this.txManager);
		}
		return interceptor;
	}

}
2.2 TransactionInterceptor 拦截原理
2.2.1 流程分析

事务执行流程

2.2.2 核心代码剖析
1. org.springframework.transaction.interceptor.TransactionAspectSupport#invokeWithinTransaction
protected Object invokeWithinTransaction(Method method, @Nullable Class<?> targetClass,
		final InvocationCallback invocation) throws Throwable {

	// If the transaction attribute is null, the method is non-transactional.
	// 获取事务注解的相关属性
	TransactionAttributeSource tas = getTransactionAttributeSource();
	final TransactionAttribute txAttr = (tas != null ? tas.getTransactionAttribute(method, targetClass) : null);
	// 从容器中获取【PlatformTransactionManager】事务管理器
	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;
	}

    ...

}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值