事务源码分析

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

# spring.handlers 配置
http\://www.springframework.org/schema/tx=org.springframework.transaction.config.TxNamespaceHandler

TxNamespaceHandlerinit() 方法注册了标签解析器,其中 <tx:annotation-driven/> 对应 AnnotationDrivenBeanDefinitionParser

public class TxNamespaceHandler extends NamespaceHandlerSupport {
    @Override
    public void init() {
        // 解析 <tx:advice/> 标签(XML 方式配置事务通知)
        registerBeanDefinitionParser("advice", new TxAdviceBeanDefinitionParser());
        // 解析 <tx:annotation-driven/> 标签(注解方式开启事务)
        registerBeanDefinitionParser("annotation-driven", new AnnotationDrivenBeanDefinitionParser());
        // 解析 <tx:jta-transaction-manager/> 标签(JTA 事务管理器)
        registerBeanDefinitionParser("jta-transaction-manager", new JtaTransactionManagerBeanDefinitionParser());
    }
}

AnnotationDrivenBeanDefinitionParser:事务核心组件的注册

AnnotationDrivenBeanDefinitionParserparse() 方法是事务配置解析的核心,根据 mode 属性(默认 proxy)决定事务增强方式,最终通过 AopAutoProxyConfigurer.configureAutoProxyCreator() 注册事务管理的核心组件。

configureAutoProxyCreator () 方法解析

该方法向容器注册 4 个关键组件,构成事务管理的基础:

public static void configureAutoProxyCreator(Element element, ParserContext parserContext) {
    // 1. 注册代理创建器:InfrastructureAdvisorAutoProxyCreator(类似 AOP 的 AnnotationAwareAspectJAutoProxyCreator)
    AopNamespaceUtils.registerAutoProxyCreatorIfNecessary(parserContext, element);
    
    // 2. 注册 TransactionAttributeSource:解析 @Transactional 注解的属性(如 propagation、isolation)
    RootBeanDefinition sourceDef = new RootBeanDefinition(AnnotationTransactionAttributeSource.class);
    String sourceName = parserContext.getReaderContext().registerWithGeneratedName(sourceDef);
    
    // 3. 注册 TransactionInterceptor:事务增强的具体实现(环绕通知,负责事务的创建、提交、回滚)
    RootBeanDefinition interceptorDef = new RootBeanDefinition(TransactionInterceptor.class);
    interceptorDef.getPropertyValues().add("transactionAttributeSource", new RuntimeBeanReference(sourceName));
    String interceptorName = parserContext.getReaderContext().registerWithGeneratedName(interceptorDef);
    
    // 4. 注册 BeanFactoryTransactionAttributeSourceAdvisor:事务切面(关联切入点和增强器)
    RootBeanDefinition advisorDef = new RootBeanDefinition(BeanFactoryTransactionAttributeSourceAdvisor.class);
    advisorDef.getPropertyValues().add("transactionAttributeSource", new RuntimeBeanReference(sourceName));
    advisorDef.getPropertyValues().add("adviceBeanName", interceptorName); // 关联 TransactionInterceptor
    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())触发代理创建:

// AbstractAutoProxyCreator 中的核心方法
@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 注解:

public boolean matches(Method method, Class<?> targetClass) {
    // 跳过 TransactionalProxy 类型的 Bean(代理对象本身)
    if (targetClass != null && TransactionalProxy.class.isAssignableFrom(targetClass)) {
        return false;
    }
    // 通过 TransactionAttributeSource 解析 @Transactional 注解
    TransactionAttributeSource tas = getTransactionAttributeSource();
    return (tas == null || tas.getTransactionAttribute(method, targetClass) != null);
}
注解解析:AnnotationTransactionAttributeSource

AnnotationTransactionAttributeSourcegetTransactionAttribute() 方法负责解析 @Transactional 注解,提取事务属性(传播行为、隔离级别、超时时间等):

// AbstractFallbackTransactionAttributeSource 中的核心逻辑
public TransactionAttribute getTransactionAttribute(Method method, Class<?> targetClass) {
    // 缓存 key:方法 + 目标类
    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;
}

// 解析 @Transactional 注解的核心逻辑
protected TransactionAttribute computeTransactionAttribute(Method method, Class<?> targetClass) {
    // 非 public 方法默认不支持事务(可通过配置修改)
    if (allowPublicMethodsOnly() && !Modifier.isPublic(method.getModifiers())) {
        return null;
    }
    
    // 优先解析方法上的 @Transactional
    TransactionAttribute txAttr = findTransactionAttribute(specificMethod);
    if (txAttr != null) {
        return txAttr;
    }
    
    // 其次解析类上的 @Transactional
    txAttr = findTransactionAttribute(specificMethod.getDeclaringClass());
    if (txAttr != null && ClassUtils.isUserLevelMethod(method)) {
        return txAttr;
    }
    
    return null;
}

事务增强的执行:TransactionInterceptor 的核心逻辑

当目标方法被代理后,调用会被 TransactionInterceptor 拦截,其 invoke() 方法是事务管理的核心,负责事务的创建、目标方法执行、提交 / 回滚。

1. invoke () 方法:事务执行的入口

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:获取事务属性和事务管理器
protected Object invokeWithinTransaction(Method method, Class<?> targetClass, InvocationCallback invocation) {
    // 1. 获取 @Transactional 注解的属性(传播行为、隔离级别等)
    final TransactionAttribute txAttr = getTransactionAttributeSource().getTransactionAttribute(method, targetClass);
    // 2. 获取事务管理器(如 DataSourceTransactionManager,由 <tx:annotation-driven transaction-manager=""/> 指定)
    final PlatformTransactionManager tm = determineTransactionManager(txAttr);
    // 3. 方法唯一标识(用于事务名称)
    final String joinpointIdentification = methodIdentification(method, targetClass, txAttr);
    
    // 后续逻辑:根据事务管理器类型处理事务
}
步骤 2:创建事务(核心)

通过 createTransactionIfNecessary() 方法创建事务,最终调用事务管理器的 getTransaction() 方法:

protected TransactionInfo createTransactionIfNecessary(PlatformTransactionManager tm, TransactionAttribute txAttr, String joinpointIdentification) {
    // 1. 生成事务名称(默认使用方法全限定名)
    if (txAttr != null && txAttr.getName() == null) {
        txAttr = new DelegatingTransactionAttribute(txAttr) {
            @Override
            public String getName() {
                return joinpointIdentification;
            }
        };
    }
    
    // 2. 调用事务管理器获取事务状态(包含连接信息、是否新事务等)
    TransactionStatus status = (txAttr != null && tm != null) ? tm.getTransaction(txAttr) : null;
    
    // 3. 封装事务信息(绑定到当前线程)
    return prepareTransactionInfo(tm, txAttr, joinpointIdentification, status);
}
事务管理器的 getTransaction () 方法

DataSourceTransactionManager 为例,其 getTransaction() 方法(继承自 AbstractPlatformTransactionManager)处理事务创建逻辑:

public final TransactionStatus getTransaction(TransactionDefinition definition) throws TransactionException {
    // 1. 获取当前线程的事务(从 ThreadLocal 中获取 ConnectionHolder)
    Object transaction = doGetTransaction();
    
    // 2. 判断当前是否已有事务
    if (isExistingTransaction(transaction)) {
        // 存在事务:根据传播行为处理(如 PROPAGATION_REQUIRED 加入现有事务)
        return handleExistingTransaction(definition, transaction, debugEnabled);
    }
    
    // 3. 不存在事务:根据传播行为处理(如 PROPAGATION_REQUIRED 创建新事务)
    if (definition.getPropagationBehavior() == TransactionDefinition.PROPAGATION_REQUIRED) {
        // 挂起当前资源(为空)
        SuspendedResourcesHolder suspendedResources = suspend(null);
        try {
            // 创建新事务状态
            DefaultTransactionStatus status = newTransactionStatus(definition, transaction, true, ...);
            // 开始事务(获取连接、设置自动提交为 false 等)
            doBegin(transaction, definition);
            return status;
        } catch (Exception ex) {
            resume(null, suspendedResources); // 异常时恢复
            throw ex;
        }
    }
}

doBegin ():事务的具体初始化

DataSourceTransactionManagerdoBegin() 方法负责初始化事务(以 JDBC 为例):

protected void doBegin(Object transaction, TransactionDefinition definition) {
    DataSourceTransactionObject txObject = (DataSourceTransactionObject) transaction;
    Connection con = null;
    
    try {
        // 1. 获取数据库连接(从数据源或 ThreadLocal 中)
        if (!txObject.hasConnectionHolder()) {
            Connection newCon = this.dataSource.getConnection();
            txObject.setConnectionHolder(new ConnectionHolder(newCon), true);
        }
        
        // 2. 配置连接(关闭自动提交,由 Spring 控制事务)
        con = txObject.getConnectionHolder().getConnection();
        if (con.getAutoCommit()) {
            txObject.setMustRestoreAutoCommit(true);
            con.setAutoCommit(false); // 核心:关闭自动提交
        }
        
        // 3. 设置隔离级别(若定义)
        Integer previousIsolationLevel = DataSourceUtils.prepareConnectionForTransaction(con, definition);
        txObject.setPreviousIsolationLevel(previousIsolationLevel);
        
        // 4. 标记事务激活状态
        txObject.getConnectionHolder().setTransactionActive(true);
    } catch (SQLException ex) {
        throw new CannotCreateTransactionException("Could not open JDBC Connection", ex);
    }
}
步骤 3:执行目标方法
try {
    // 执行目标方法(如 Service 的业务方法)
    retVal = invocation.proceedWithInvocation();
} catch (Throwable ex) {
    // 异常处理:根据 @Transactional 的 rollbackFor 决定是否回滚
    completeTransactionAfterThrowing(txInfo, ex);
    throw ex;
}
步骤 4:提交或回滚事务
  • 正常执行:调用 commitTransactionAfterReturning(txInfo) 提交事务;
  • 异常执行:调用 completeTransactionAfterThrowing(txInfo, ex) 回滚事务。
提交事务(doCommit ())
protected void doCommit(DefaultTransactionStatus status) {
    DataSourceTransactionObject txObject = (DataSourceTransactionObject) status.getTransaction();
    Connection con = txObject.getConnectionHolder().getConnection();
    try {
        con.commit(); // 调用 JDBC 连接的 commit()
    } catch (SQLException ex) {
        throw new TransactionSystemException("Could not commit JDBC transaction", ex);
    }
}
回滚事务(doRollback ())
protected void doRollback(DefaultTransactionStatus status) {
    DataSourceTransactionObject txObject = (DataSourceTransactionObject) status.getTransaction();
    Connection con = txObject.getConnectionHolder().getConnection();
    try {
        con.rollback(); // 调用 JDBC 连接的 rollback()
    } catch (SQLException ex) {
        throw new TransactionSystemException("Could not roll back JDBC transaction", ex);
    }
}

事务传播行为的处理:核心场景分析

事务传播行为定义了 “当一个事务方法调用另一个事务方法时,事务如何传播”(如是否新建事务、加入现有事务等)。AbstractPlatformTransactionManagergetTransaction() 方法是传播行为处理的核心。

1. 常见传播行为的处理逻辑

  • PROPAGATION_REQUIRED(默认):如果当前有事务,则加入;否则新建事务。
if (isExistingTransaction(transaction)) {
      // 存在事务:加入当前事务
    return handleExistingTransaction(definition, transaction, debugEnabled);
  } else {
    // 不存在事务:新建事务
      return createNewTransaction(definition);
}
  • PROPAGATION_REQUIRES_NEW:无论当前是否有事务,都新建事务(挂起当前事务)。

    if (isExistingTransaction(transaction)) {
          // 挂起当前事务
        SuspendedResourcesHolder suspended = suspend(transaction);
          try {
            // 新建事务
              return createNewTransaction(definition);
        } catch (Exception ex) {
              resumeAfterCompletion(transaction, suspended); // 异常时恢复
            throw ex;
          }
    }
  • PROPAGATION_NESTED:在当前事务中创建嵌套事务(依赖数据库的保存点 Savepoint)。

总结:事务管理的本质与核心链路

Spring 事务管理的本质是 “基于 AOP 的环绕通知”,通过以下链路实现:

  1. 配置解析<tx:annotation-driven/> 触发 AnnotationDrivenBeanDefinitionParser,注册 InfrastructureAdvisorAutoProxyCreatorTransactionInterceptor 等核心组件;

  2. 代理创建InfrastructureAdvisorAutoProxyCreator 在 Bean 初始化后,为标注 @Transactional 的 Bean 生成代理;

  3. 方法拦截:代理方法被调用时,TransactionInterceptor 拦截并执行 invokeWithinTransaction()

  4. 事务生命周期:

    • 解析 @Transactional 属性,获取事务管理器;
  • 根据传播行为创建 / 加入事务(获取连接、关闭自动提交);
    • 执行目标方法;
    • 正常则提交事务,异常则根据 rollbackFor 回滚