Spring 事务源码全解析:从 <tx:annotation-driven/> 到事务提交的完整链路
Spring 事务管理是 AOP 思想的典型应用,其核心是通过 <tx:annotation-driven/> 配置开启注解式事务,底层依赖 “自定义标签解析→事务组件注册→AOP 代理增强→事务生命周期管理” 的完整机制。从配置解析到事务执行,逐环节拆解 Spring 事务的实现原理。
事务配置的解析:<tx:annotation-driven/> 标签处理
与 AOP 的 <aop:aspectj-autoproxy/> 类似,<tx:annotation-driven/> 是 Spring 事务的核心配置标签,其解析依赖自定义标签机制,最终目的是向容器注册事务管理的核心组件。
自定义标签映射与处理器初始化
<tx:annotation-driven/> 的命名空间为 http://www.springframework.org/schema/tx,Spring 通过 META-INF/spring.handlers 映射到对应的处理器 TxNamespaceHandler:
1 2
| http\://www.springframework.org/schema/tx=org.springframework.transaction.config.TxNamespaceHandler
|
TxNamespaceHandler 的 init() 方法注册了标签解析器,其中 <tx:annotation-driven/> 对应 AnnotationDrivenBeanDefinitionParser:
1 2 3 4 5 6 7 8 9 10 11
| public class TxNamespaceHandler extends NamespaceHandlerSupport { @Override public void init() { registerBeanDefinitionParser("advice", new TxAdviceBeanDefinitionParser()); registerBeanDefinitionParser("annotation-driven", new AnnotationDrivenBeanDefinitionParser()); registerBeanDefinitionParser("jta-transaction-manager", new JtaTransactionManagerBeanDefinitionParser()); } }
|
AnnotationDrivenBeanDefinitionParser:事务核心组件的注册
AnnotationDrivenBeanDefinitionParser 的 parse() 方法是事务配置解析的核心,根据 mode 属性(默认 proxy)决定事务增强方式,最终通过 AopAutoProxyConfigurer.configureAutoProxyCreator() 注册事务管理的核心组件。
该方法向容器注册 4 个关键组件,构成事务管理的基础:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
| public static void configureAutoProxyCreator(Element element, ParserContext parserContext) { AopNamespaceUtils.registerAutoProxyCreatorIfNecessary(parserContext, element); RootBeanDefinition sourceDef = new RootBeanDefinition(AnnotationTransactionAttributeSource.class); String sourceName = parserContext.getReaderContext().registerWithGeneratedName(sourceDef); RootBeanDefinition interceptorDef = new RootBeanDefinition(TransactionInterceptor.class); interceptorDef.getPropertyValues().add("transactionAttributeSource", new RuntimeBeanReference(sourceName)); String interceptorName = parserContext.getReaderContext().registerWithGeneratedName(interceptorDef); RootBeanDefinition advisorDef = new RootBeanDefinition(BeanFactoryTransactionAttributeSourceAdvisor.class); advisorDef.getPropertyValues().add("transactionAttributeSource", new RuntimeBeanReference(sourceName)); advisorDef.getPropertyValues().add("adviceBeanName", interceptorName); String txAdvisorBeanName = TransactionManagementConfigUtils.TRANSACTION_ADVISOR_BEAN_NAME; parserContext.getRegistry().registerBeanDefinition(txAdvisorBeanName, advisorDef); }
|
4 个核心组件的作用
| 组件名称 |
作用 |
| InfrastructureAdvisorAutoProxyCreator |
代理创建器:为标注 @Transactional 的 Bean 生成 AOP 代理 |
| AnnotationTransactionAttributeSource |
注解解析器:解析 @Transactional 的属性(传播行为、隔离级别等) |
| TransactionInterceptor |
事务拦截器:环绕通知,负责事务的创建、提交、回滚(核心执行逻辑) |
| BeanFactoryTransactionAttributeSourceAdvisor |
事务切面:关联切入点(哪些方法需要事务)和增强器(TransactionInterceptor) |
事务代理的创建:InfrastructureAdvisorAutoProxyCreator 的作用
InfrastructureAdvisorAutoProxyCreator 是事务代理的创建者,其类结构与 AOP 的 AnnotationAwareAspectJAutoProxyCreator 相似,均继承自 AbstractAdvisorAutoProxyCreator,核心逻辑是 “查找匹配的 Advisor 并为 Bean 生成代理”。
![事务解析]()
事务解析
1. 代理创建的触发时机
与 AOP 代理相同,InfrastructureAdvisorAutoProxyCreator 实现了 BeanPostProcessor 接口,在 Bean 初始化阶段(postProcessAfterInitialization())触发代理创建:
1 2 3 4 5 6 7 8 9 10 11
| @Override public Object postProcessAfterInitialization(Object bean, String beanName) { if (bean != null) { Object cacheKey = getCacheKey(bean.getClass(), beanName); if (this.earlyProxyReferences.remove(cacheKey) != bean) { return wrapIfNecessary(bean, beanName, cacheKey); } } return bean; }
|
2. 匹配事务切面:BeanFactoryTransactionAttributeSourceAdvisor
wrapIfNecessary() 方法会查找容器中所有 Advisor,并筛选出与当前 Bean 匹配的 BeanFactoryTransactionAttributeSourceAdvisor(事务切面)。该 Advisor 的匹配逻辑由其切入点 TransactionAttributeSourcePointcut 决定。
切入点匹配:TransactionAttributeSourcePointcut
TransactionAttributeSourcePointcut 通过 matches(Method method, Class<?> targetClass) 方法判断方法是否需要事务增强,核心是检查方法或类上是否有 @Transactional 注解:
1 2 3 4 5 6 7 8 9
| public boolean matches(Method method, Class<?> targetClass) { if (targetClass != null && TransactionalProxy.class.isAssignableFrom(targetClass)) { return false; } TransactionAttributeSource tas = getTransactionAttributeSource(); return (tas == null || tas.getTransactionAttribute(method, targetClass) != null); }
|
注解解析:AnnotationTransactionAttributeSource
AnnotationTransactionAttributeSource 的 getTransactionAttribute() 方法负责解析 @Transactional 注解,提取事务属性(传播行为、隔离级别、超时时间等):
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37
| public TransactionAttribute getTransactionAttribute(Method method, Class<?> targetClass) { Object cacheKey = getCacheKey(method, targetClass); TransactionAttribute cached = this.attributeCache.get(cacheKey); if (cached != null) { return (cached == NULL_TRANSACTION_ATTRIBUTE) ? null : cached; } TransactionAttribute txAttr = computeTransactionAttribute(method, targetClass); this.attributeCache.put(cacheKey, txAttr != null ? txAttr : NULL_TRANSACTION_ATTRIBUTE); return txAttr; }
protected TransactionAttribute computeTransactionAttribute(Method method, Class<?> targetClass) { if (allowPublicMethodsOnly() && !Modifier.isPublic(method.getModifiers())) { return null; } TransactionAttribute txAttr = findTransactionAttribute(specificMethod); if (txAttr != null) { return txAttr; } txAttr = findTransactionAttribute(specificMethod.getDeclaringClass()); if (txAttr != null && ClassUtils.isUserLevelMethod(method)) { return txAttr; } return null; }
|
事务增强的执行:TransactionInterceptor 的核心逻辑
当目标方法被代理后,调用会被 TransactionInterceptor 拦截,其 invoke() 方法是事务管理的核心,负责事务的创建、目标方法执行、提交 / 回滚。
1. invoke () 方法:事务执行的入口
1 2 3 4 5 6 7 8 9 10 11 12
| public Object invoke(final MethodInvocation invocation) throws Throwable { Class<?> targetClass = (invocation.getThis() != null ? AopUtils.getTargetClass(invocation.getThis()) : null); return invokeWithinTransaction(invocation.getMethod(), targetClass, new InvocationCallback() { @Override public Object proceedWithInvocation() throws Throwable { return invocation.proceed(); } }); }
|
2. invokeWithinTransaction ():事务的完整生命周期
该方法包含事务管理的全部逻辑:创建事务→执行目标方法→提交 / 回滚事务,核心流程如下:
步骤 1:获取事务属性和事务管理器
1 2 3 4 5 6 7 8 9 10
| protected Object invokeWithinTransaction(Method method, Class<?> targetClass, InvocationCallback invocation) { final TransactionAttribute txAttr = getTransactionAttributeSource().getTransactionAttribute(method, targetClass); final PlatformTransactionManager tm = determineTransactionManager(txAttr); final String joinpointIdentification = methodIdentification(method, targetClass, txAttr); }
|
步骤 2:创建事务(核心)
通过 createTransactionIfNecessary() 方法创建事务,最终调用事务管理器的 getTransaction() 方法:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
| protected TransactionInfo createTransactionIfNecessary(PlatformTransactionManager tm, TransactionAttribute txAttr, String joinpointIdentification) { if (txAttr != null && txAttr.getName() == null) { txAttr = new DelegatingTransactionAttribute(txAttr) { @Override public String getName() { return joinpointIdentification; } }; } TransactionStatus status = (txAttr != null && tm != null) ? tm.getTransaction(txAttr) : null; return prepareTransactionInfo(tm, txAttr, joinpointIdentification, status); }
|
事务管理器的 getTransaction () 方法
以 DataSourceTransactionManager 为例,其 getTransaction() 方法(继承自 AbstractPlatformTransactionManager)处理事务创建逻辑:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26
| public final TransactionStatus getTransaction(TransactionDefinition definition) throws TransactionException { Object transaction = doGetTransaction(); if (isExistingTransaction(transaction)) { return handleExistingTransaction(definition, transaction, debugEnabled); } if (definition.getPropagationBehavior() == TransactionDefinition.PROPAGATION_REQUIRED) { SuspendedResourcesHolder suspendedResources = suspend(null); try { DefaultTransactionStatus status = newTransactionStatus(definition, transaction, true, ...); doBegin(transaction, definition); return status; } catch (Exception ex) { resume(null, suspendedResources); throw ex; } } }
|
doBegin ():事务的具体初始化
DataSourceTransactionManager 的 doBegin() 方法负责初始化事务(以 JDBC 为例):
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28
| protected void doBegin(Object transaction, TransactionDefinition definition) { DataSourceTransactionObject txObject = (DataSourceTransactionObject) transaction; Connection con = null; try { if (!txObject.hasConnectionHolder()) { Connection newCon = this.dataSource.getConnection(); txObject.setConnectionHolder(new ConnectionHolder(newCon), true); } con = txObject.getConnectionHolder().getConnection(); if (con.getAutoCommit()) { txObject.setMustRestoreAutoCommit(true); con.setAutoCommit(false); } Integer previousIsolationLevel = DataSourceUtils.prepareConnectionForTransaction(con, definition); txObject.setPreviousIsolationLevel(previousIsolationLevel); txObject.getConnectionHolder().setTransactionActive(true); } catch (SQLException ex) { throw new CannotCreateTransactionException("Could not open JDBC Connection", ex); } }
|
步骤 3:执行目标方法
1 2 3 4 5 6 7 8
| try { retVal = invocation.proceedWithInvocation(); } catch (Throwable ex) { completeTransactionAfterThrowing(txInfo, ex); throw ex; }
|
步骤 4:提交或回滚事务
- 正常执行:调用
commitTransactionAfterReturning(txInfo) 提交事务;
- 异常执行:调用
completeTransactionAfterThrowing(txInfo, ex) 回滚事务。
提交事务(doCommit ())
1 2 3 4 5 6 7 8 9
| protected void doCommit(DefaultTransactionStatus status) { DataSourceTransactionObject txObject = (DataSourceTransactionObject) status.getTransaction(); Connection con = txObject.getConnectionHolder().getConnection(); try { con.commit(); } catch (SQLException ex) { throw new TransactionSystemException("Could not commit JDBC transaction", ex); } }
|
回滚事务(doRollback ())
1 2 3 4 5 6 7 8 9
| protected void doRollback(DefaultTransactionStatus status) { DataSourceTransactionObject txObject = (DataSourceTransactionObject) status.getTransaction(); Connection con = txObject.getConnectionHolder().getConnection(); try { con.rollback(); } catch (SQLException ex) { throw new TransactionSystemException("Could not roll back JDBC transaction", ex); } }
|
事务传播行为的处理:核心场景分析
事务传播行为定义了 “当一个事务方法调用另一个事务方法时,事务如何传播”(如是否新建事务、加入现有事务等)。AbstractPlatformTransactionManager 的 getTransaction() 方法是传播行为处理的核心。
1. 常见传播行为的处理逻辑
- PROPAGATION_REQUIRED(默认):如果当前有事务,则加入;否则新建事务。
1 2 3 4 5 6 7
| if (isExistingTransaction(transaction)) { return handleExistingTransaction(definition, transaction, debugEnabled); } else { return createNewTransaction(definition); }
|
总结:事务管理的本质与核心链路
Spring 事务管理的本质是 “基于 AOP 的环绕通知”,通过以下链路实现:
配置解析:<tx:annotation-driven/> 触发 AnnotationDrivenBeanDefinitionParser,注册 InfrastructureAdvisorAutoProxyCreator、TransactionInterceptor 等核心组件;
代理创建:InfrastructureAdvisorAutoProxyCreator 在 Bean 初始化后,为标注 @Transactional 的 Bean 生成代理;
方法拦截:代理方法被调用时,TransactionInterceptor 拦截并执行 invokeWithinTransaction();
事务生命周期:
- 解析
@Transactional 属性,获取事务管理器;
- 根据传播行为创建 / 加入事务(获取连接、关闭自动提交);
- 执行目标方法;
- 正常则提交事务,异常则根据
rollbackFor 回滚
v1.3.10