
spring 的 `@transactional` 并非直接对应某个单一的 `advice` 类,而是由 `transactioninterceptor`(即环绕通知)配合 `transactionattributesource` 和事务管理器协同完成,其代理创建由 `infrastructureadvisorautoproxycreator` 触发。
在 Spring AOP 体系中,@Transactional 的底层实现并非基于传统的 BeforeAdvice 或 AfterReturningAdvice,而是一个标准的 MethodInterceptor —— 即 org.springframework.transaction.interceptor.TransactionInterceptor。它本质上是一个 环绕通知(Around Advice),负责在目标方法执行前后开启、提交或回滚事务。
TransactionInterceptor
继承自 TransactionAspectSupport,重写了 invoke() 方法,在反射调用业务方法前获取事务属性、开启事务;方法正常返回后提交,抛出异常则按 rollbackFor/noRollbackFor 规则决定是否回滚。
✅ 它就是你所寻找的“实际执行事务逻辑”的 Advice。
TransactionAttributeSource
负责从 @Transactional 注解中提取事务配置(如 propagation、isolation、timeout 等),默认实现为 AnnotationTransactionAttributeSource。
TransactionAdvisor
将 TransactionInterceptor(advice)与 TransactionAttributeSource(pointcut 信息)封装为一个完整的 Advisor,供 AOP 框架织入。
代理创建入口:InfrastructureAdvisorAutoProxyCreator
这是 Spring 内置的 BeanPostProcessor,在 Bean 初始化后(postProcessAfterInitialization 阶段)扫描所有 Advisor(包括 TransactionAdvisor),对匹配的 Bean 创建 JDK 动态代理或 CGLIB 代理。
? 在 IntelliJ 中,可在此类的 wrapIfNecessary() 方法设断点,逐步跟踪代理生成及 TransactionInterceptor 的注入过程。
@Service
public class OrderService {
@Transactional
public void createOrder() {
System.out.println("Creating order...");
// 数据库操作
}
}当该 Bean 被 Spring 容器管理时,实际注入的 OrderService 是一个代理对象。调用 createOrder() 时,真正执行的是 TransactionInterceptor.invoke(),而非原始方法。
掌握这一机制,不仅能理解事务如何工作,也为定制化事务行为(如扩展 TransactionAttributeSource 或替换 TransactionInterceptor)打下坚实基础。