源码小说CodeStory
登录
上一章

41,752 字 · 约 104 分钟

下一章
字体

主题

版式

第26章 卷七 · 要么全做 · 自己人喊自己人:事务的坑

⾃⼰⼈喊⾃⼰⼈:事务的坑「我不是语⾔特性。我是⼀个站在⻔⼝的第三者。 你所有的困惑,归根到底只有⼀个问题:这⼀次,你有没有从我身上过?」 —— TransactionInterceptor 的⾃⽩开场:⼀份没有报错的事故报告线上出过⼀次事故。订单落库成功了,库存却没扣。查⽇志,没有异常;查代码, @Transactional 明明⽩⽩写在⽅法上;查配置,事务管理器好好地躺在容器⾥。所有能查的都查了,所有能查的都是对的。

⼀个星期后有⼈发现,那个 @Transactional ⽅法是被同⼀个类⾥的另⼀个⽅法⽤ this. 调过去的。

我要在本章⼀开始就把这句话钉死,因为它是后⾯六个坑的共同地基:

@Transactional 从来不是⼀个"标记"。它是⼀道刻在壳上的⼯序。 ⽽壳只拦得住从外⾯进来的调⽤。

坊⾥的规矩是"递到你⼿上的常常不是原件,是套了壳的原件"(第 21–23 章讲的就是这层壳怎么套上去)。这⼀章讲的是这层壳的背⾯:同⼀个机制,把事务、缓存、重试免费挂上去的那份威⼒,和让 @Transactional 静默失效的那份坑,是同⼀件事的正反两⾯。

全部魔法只发⽣在⼀个⽅法⾥:

// [framework] spring-tx/src/main/java/org/springframework/transaction/interceptor/TransactionInterceptor.java:123@Override

public @Nullable Object invoke(MethodInvocation invocation) throws Throwable {
Class<?> targetClass = (invocation.getThis() != null ? AopUtils.getTargetClass(invocation.getThis()) : null);
return invokeWithinTransaction(invocation.getMethod(), targetClass, new InvocationCallback() { ... });
}

它是⼀个标准的 AOP Alliance MethodInterceptor 。它要被调⽤,前提是这次调⽤⾛进了拦截链。

于是六个坑可以⼲净地劈成两半:

坑 根因路没通——拦截器压根没被调到 ① ⾃调⽤、② ⾮ public、④ @PostConstruct 请求没经过壳 / 壳还没⽣出来路通了但⾛岔了 ③ 受检异常不回滚、⑤ 选错事务管理器、⑥ 时序错位 语义与默认值的理解偏差前三个,你看不到任何拦截器⽇志。后三个,拦截器⽇志好好的,数据不对。

⼀、物理地基:代理和原件,是两个对象讲任何⼀个坑之前,必须先把这⼀条钉死——⽽且它⽐⼤多数⼈以为的更彻底。

JDK 动态代理是两个对象,这个没⼈会误解:代理实现接⼝,内部持有⼀个 target 引⽤。

真正被误解的是 CGLIB。流传最⼴的说法是"CGLIB ⽣成⼀个⼦类,⽅法⾥调 super.method() ,所以 this 就是代理本身"。Spring 的 CGLIB 代理不是这么⼲的。

// [framework] spring-aop/src/main/java/org/springframework/aop/framework/CglibAopProxy.java:715

public @Nullable Object intercept(Object proxy, Method method, Object[] args, MethodProxy methodProxy) throws Throwable {
Object oldProxy = null;
boolean setProxyContext = false;
Object target = null;
TargetSource targetSource = this.advised.getTargetSource();
try {
if (this.advised.isExposeProxy()) {
oldProxy = AopContext.setCurrentProxy(proxy); // :723
setProxyContext = true;
}

// Get as late as possible to minimize the time we "own" the target, in case it comes from a pool...

target = targetSource.getTarget(); // :727 ←⼜是另⼀个对象
Class<?> targetClass = (target != null ? target.getClass() : null);
List<Object> chain = this.advised.getInterceptorsAndDynamicInterceptionAdvice(method, targetClass);
Object retVal;
if (chain.isEmpty()) {
@Nullable Object[] argsToUse = AopProxyUtils.adaptArgumentsIfNecessary(method, args);
retVal = AopUtils.invokeJoinpointUsingReflection(target, method, argsToUse); // :739
}
else {
retVal = new ReflectiveMethodInvocation(proxy, target, method, args, targetClass, chain).proceed();
}
return processReturnType(proxy, target, method, args, retVal);
}

做了什么:拿 target,组拦截链,反射打过去。

注意那个被完全忽略的 methodProxy 参数。 CGLIB 提供了 methodProxy.invokeSuper() 这条"调⽗类实现"的快路,Spring ⼀次都没⽤。它⽤的是targetSource.getTarget() 拿到的独⽴实例,再反射调过去。

为什么这么设计:因为 TargetSource 是可替换的——池化、热切换、按请求换实例,全靠"target 是外部拿来的"这个前提。⼀旦⽤ invokeSuper() ,target 就被焊死成"代理⾃⼰",这些能⼒全部作废。

坑在哪:于是 Spring ⽣成的那个 CGLIB ⼦类,是⼀个空壳。它的字段全是 null——它的构造过程从不跑你的初始化逻辑,它只负责转发。这不是我的推测,框架⾃⼰在⽇志⾥写着:

// [framework] spring-aop/src/main/java/org/springframework/aop/framework/CglibAopProxy.java:309-311

logger.debug("Final method [" + method + "] cannot get proxied via CGLIB: " +

"Calls to this method will NOT be routed to the target instance and " +

"might lead to NPEs against uninitialized fields in the proxy instance.");

"might lead to NPEs against uninitialized fields in the proxy instance"——这⼀句把空壳模型交代得⼲⼲净净:⼀旦某个⽅法没被转发出去(⽐如 final ),你的业务代码就会在⼀个字段全空的壳上执⾏。

记住这张画⾯,它是本章所有推理的底座: 壳是空的,本⼈在壳的兜⾥。壳只负责"有⼈从外⾯敲⻔时,替本⼈接⼀下"。

⼆、坑⼀:⾃⼰⼈在壳⾥⾯喊⾃⼰⼈2.1 物理原因:它连被通知的机会都没有target ⾥写 this.doWork() , this 是本⼈,不是壳。JVM 层⾯这就是⼀条普通的 invokevirtual ,直接查本⼈的⽅法表,⼀步到位。没有任何⼀个环节有机会拐到TransactionInterceptor 上。

这⼀点值得反复强调:不是 Spring "没检测到",不是它"偷懒没做"。是它根本没被告知这件事发⽣过。

框架⾃⼰的措辞极其⼲脆:

"Please note that proxy mode allows for interception of calls through the proxy only. Local calls within the same class cannot get intercepted that way; an

Transactional annotation on such a method within a local call will be ignored since Spring's interceptor does not even kick in for such a runtime scenario."

——[framework] spring-tx/src/main/java/org/springframework/transaction/annotation/EnableTransactionManagement.java:186-191 ( mode() 的
javadoc)

"does not even kick in"。连启动都没启动。

参考⼿册同⼀处([framework] framework-docs/modules/ROOT/pages/data-access/transaction/declarative/annotations.adoc:219-222 )措辞更冷:self-invocation

"does not lead to an actual transaction at runtime even if the invoked method is marked with @Transactional "。

排查特征(记住这三条,能省你半天): 1. ⽇志⾥ TransactionAspectSupport ⼀⾏ trace 都没有(正常应该有 "Getting transaction for [...]"); 2. 在⽅法⾥打

TransactionSynchronizationManager.isActualTransactionActive() ([framework] spring-
tx/src/main/java/org/springframework/transaction/support/TransactionSynchronizationManager.java:499 ),返回 false ; 3. 注解、配置、事务管理器全都是对的

——这正是它难查的原因。

2.2 解法 A: AopContext.currentProxy() ——框架⾃⼰都在劝你别⽤Spring 留了⼀个逃⽣舱,全类只有⼏⼗⾏:

// [framework] spring-aop/src/main/java/org/springframework/aop/framework/AopContext.java:51

private static final ThreadLocal<Object> currentProxy = new NamedThreadLocal<>("Current AOP proxy");

// :67

public static Object currentProxy() throws IllegalStateException {
Object proxy = currentProxy.get();
if (proxy == null) {
throw new IllegalStateException(

"Cannot find current proxy: Set 'exposeProxy' property on Advised to 'true' to make it available, and " +

"ensure that AopContext.currentProxy() is invoked in the same thread as the AOP invocation context.");
}
return proxy;
}

// :84 ←注意:没有 public

static @Nullable Object setCurrentProxy(@Nullable Object proxy) { ... }

做了什么:壳在转发之前,把"我⾃⼰"塞进⼀条挂在本⼈身上的绳(ThreadLocal);本⼈在⽅法⾥可以顺着绳把壳摸出来,再从壳上重新敲⼀次⻔——这⼀次就过⼯序了。

为什么这么设计:写⼊端 setCurrentProxy 是包级私有的( AopContext.java:84 ),只有 org.springframework.aop.framework 包内部能塞值。塞值点全书只有三

处: JdkDynamicAopProxy.java:196 (finally 复原在 :252 )、 CglibAopProxy.java:723 (复原在 :753 ),外加 CglibAopProxy.java:516 / :572 那两个"这⽅法没有

advice、但因为开了 exposeProxy 仍要塞绳"的专⽤回调。关得死死的,不给你乱塞的机会。

代价清单(这部分是最容易被博客写漏的,我按重要性排):

代价 1:必须显式开 exposeProxy ,默认关闭。 ⽽且——// [framework] spring-aop/src/main/java/org/springframework/aop/framework/ProxyConfig.java:116

* <p>Default is "false", in order to avoid unnecessary extra interception.
  • This means that no guarantees are provided that AopContext access will
  • work consistently within any method of the advised object.
AopContext 的类 javadoc 把成本写在最显眼处:"Spring's AOP framework does not expose proxies by default, as there is a performance cost in doing so."([framework]
AopContext.java:31-32 )。

这⾥有⼀处我要批评 Spring 的地⽅,⽽且是本章最实在的⼀条:开关藏错了地⽅。

@EnableTransactionManagement 有四个属性—— proxyTargetClass ([framework] EnableTransactionManagement.java:182 )、 mode ( :194 )、 order ( :201 )、
rollbackOn ( :222 )——没有 exposeProxy 。要开只能去写 @EnableAspectJAutoProxy(exposeProxy = true) ([framework] spring-
context/src/main/java/org/springframework/context/annotation/EnableAspectJAutoProxy.java:137 ,默认 false ),或者⾃⼰调
AopConfigUtils.forceAutoProxyCreatorToExposeProxy(registry) ([framework] spring-
aop/src/main/java/org/springframework/aop/config/AopConfigUtils.java:104-105 )。

⽽ Boot 侧——我在整个 [boot] 仓库 grep 了 exposeProxy 和 expose-proxy 两个串,零命中。对照组: spring.aop.proxy-target-class 是有的,⽽且被事务⾃动配置直

接消费([boot] module/spring-boot-transaction/src/main/java/org/springframework/boot/transaction/autoconfigure/TransactionAutoConfiguration.java:75
/ :82 )。

也就是说:为了解决 Spring ⽣态最著名的⼀个坑,你要去打开⼀个跟事务毫⽆关系的 AspectJ 注解上的开关,⽽ Boot 连⼀⾏配置项都不给你。 这不是技术上做不到,这是⼀次态度表达——Spring 在⽤"不⽅便"劝你别⾛这条路。它做得对,但它应该在⽂档⾥说清楚,⽽不是让每个⼈⾃⼰撞⼀遍。

代价 2:返回 Object ,必须强转。 写出来是 ((OrderService) AopContext.currentProxy()).doWork() 。丑,⽽且在 JDK 代理下,强转的⽬标类型只能是接⼝。

代价 3:ThreadLocal 语义,换线程就断。 异常⽂案⾃⼰在提醒:"ensure that AopContext.currentProxy() is invoked in the same thread as the AOP invocation context"
([framework] AopContext.java:71-72 )。

代价 4:业务代码被绑死在 Spring AOP 上。 这条是框架亲⼝说的:

"However, this approach should not be used when there is a reasonable alternative, as it makes application code dependent on usage under AOP and the SpringAOP framework in particular." ——[framework] AopContext.java:34-37框架⾃⼰都在劝你别⽤。 这句话应该刻在每⼀篇推荐 AopContext 的博客顶上。

2.3 解法 B:注⼊⾃⼰

@Autowired private OrderService self; —— 拿到的是容器⾥的那个 bean,也就是壳。

这条路能⾛通,物理依据在依赖解析的最后⼀趟:

// [framework] spring-beans/src/main/java/org/springframework/beans/factory/support/DefaultListableBeanFactory.java:1992

if (result.isEmpty() && !multiple) {

// Consider self references as a final pass...// but in the case of a dependency collection, not the very same bean itself.

for (String candidate : candidateNames) {
if (isSelfReference(beanName, candidate) &&
(!(descriptor instanceof MultiElementDescriptor) || !beanName.equals(candidate)) &&
isAutowireCandidate(candidate, fallbackDescriptor)) {
addCandidateEntry(result, candidate, descriptor, requiredType);
}
}
}

精妙在哪:前⾯两趟都带着 !isSelfReference(...) 主动把⾃⼰排除掉,只有前两趟全空,才在第三趟把⾃⼰捞回来。这是⼀个刻意的"最后⼿段"设计——不⿎励,但不禁⽌。

代价: 1. 不能⽤构造器注⼊。 那是真·构造期循环依赖,直接 BeanCurrentlyInCreationException 。必须字段/setter 注⼊,或者加 @Lazy 。 2. Boot 侧默认禁⽌循环引⽤:

[boot] core/spring-boot/src/main/java/org/springframework/boot/ApplicationProperties.java:49 是 private boolean allowCircularReferences; ——

primitive,默认 false 。字段注⼊的⾃引⽤⾛的是 setter 阶段并命中上⾯那个 final pass,通常不触发该报错;但⼀旦改成构造器注⼊就会当场炸。(诚实说明:"字段注⼊⾃引⽤ +Boot 4 默认配置 100% 不报错"这⼀点我核了两侧源码路径,没有跑实际⽤例。构造器注⼊必炸这点是确定的。) 3. self.doWork() 对不熟悉这个套路的⼈是天书,必须配注释。 4.和解法 A ⼀样,依然把 AOP 的实现细节泄漏进了业务代码。

2.4 解法 C:拆类物理上最⼲净: A.outer() → B.inner() ,B 是独⽴的 bean,调⽤天然从 B 的壳上过。

代价(要诚实): 1. 可能拆出⼀个⽆意义的类。 如果 B 只有⼀个⽅法、只被 A 调⽤,那它是为框架限制付的设计税,不是领域建模的产物。别把这说成"更好的分层"。 2. 事务边界从"⼀个类内部"变成"两个 bean 之间",传播⾏为要重新想⼀遍——尤其是内层该不该 REQUIRES_NEW (这⼀点在第七节会咬⼈)。 3. 如果 B ⼜要回调 A ,循环依赖问题原地复活。

2.5 解法 D:切到 AspectJ 模式——唯⼀从物理上根除的⽅案

@EnableTransactionManagement(mode = AdviceMode.ASPECTJ) 。没有壳,直接改字节码。
"...There is no proxy involved in such a scenario; local calls will be intercepted as well." ——[framework] EnableTransactionManagement.java:145-149

切⾯实体确实在仓⾥:[framework] spring-aspects/src/main/java/org/springframework/transaction/aspectj/AnnotationTransactionAspect.aj 。Boot 侧也对它有感知——[boot] module/spring-boot-transaction/src/main/java/org/springframework/boot/transaction/autoconfigure/TransactionAutoConfiguration.java:91 的AspectJTransactionManagementConfiguration ,在容器⾥存在 AbstractTransactionAspect 时注册⼀个 LazyInitializationExcludeFilter ,保证切⾯不被懒加载。

但它有⼀条硬约束,极容易翻⻋:

"When you use this aspect, you must annotate the implementation class (or the methods within that class or both), not the interface... AspectJ follows Java's rule

that annotations on interfaces are not inherited." ——[framework] framework-docs/modules/ROOT/pages/data-access/transaction/declarative/aspectj.adoc:49-51代价:引⼊织⼊(编译期或 LTW),构建链复杂度陡增;调试栈变形;团队⼼智负担⼤。实践中极少值得。

2.6 我的态度不给"各有优劣"这种收尾。

默认选 C(拆类)。 唯⼀⼀个不把 AOP 细节写进业务代码的⽅案。 只有当"拆出来的类明显是个凑数的空壳"时,才退到 B(注⼊⾃⼰),并且必须写注释说明为什么。

A( AopContext ) 留给"改不动的⽼代码 + 已经开了 exposeProxy"的既成事实——框架⾃⼰在 AopContext.java:34-37 就写了"有合理替代⽅案时不应使⽤"。

D(AspectJ) 是核武器:只有当⾃调⽤问题在整个代码库⾥成规模、且团队已有织⼊基建时才考虑。为⼀个⽅法上织⼊,是拿⼤炮打蚊⼦。

三、坑⼆:⾮ public ⽅法——本基线的⼀次重⼤纠偏

⚠ 这⼀节要推翻⼀条流传极⼴的常识。 " @Transactional 只对 public ⽅法⽣效"——在本基线下是错的,⽽且已经错了好⼏年了。

3.1 两个默认值,别混类的默认值确实是 true :

// [framework] spring-tx/src/main/java/org/springframework/transaction/annotation/AnnotationTransactionAttributeSource.java:75

private boolean publicMethodsOnly = true;

但 @EnableTransactionManagement 注册的那个实例,显式传了 false :

// [framework] spring-tx/src/main/java/org/springframework/transaction/annotation/AbstractTransactionManagementConfiguration.java:84-92@Bean

@Role(BeanDefinition.ROLE_INFRASTRUCTURE)
public TransactionAttributeSource transactionAttributeSource() {

// Accept protected @Transactional methods on CGLIB proxies, as of 6.0

AnnotationTransactionAttributeSource tas = new AnnotationTransactionAttributeSource(false);

// Apply default rollback rule, as of 6.2

if (this.enableTx != null && this.enableTx.getEnum("rollbackOn") == RollbackOn.ALL_EXCEPTIONS) {
tas.addDefaultRollbackRule(RollbackRuleAttribute.ROLLBACK_ON_ALL_EXCEPTIONS);
}
return tas;
}

源码注释⽩纸⿊字:"Accept protected @Transactional methods on CGLIB proxies, as of 6.0"。

3.2 开关在拦截链上的哪⼀⾏// [framework] spring-tx/src/main/java/org/springframework/transaction/interceptor/AbstractFallbackTransactionAttributeSource.java:161-165

protected @Nullable TransactionAttribute computeTransactionAttribute(Method method, @Nullable Class<?> targetClass) {

// Don't allow non-public methods, as configured.

if (allowPublicMethodsOnly() && !Modifier.isPublic(method.getModifiers())) {

return null; // ←返回 null =这不是事务⽅法

}
基类的 allowPublicMethodsOnly() 默认返回 false ([framework] AbstractFallbackTransactionAttributeSource.java:224 ),⼦类覆写后返回⾃⼰的
publicMethodsOnly 字段([framework] AnnotationTransactionAttributeSource.java:215-216 )。
返回 null 之后⼀路传导: hasTransactionAttribute 变成 false([framework] AbstractFallbackTransactionAttributeSource.java:91-
92 ), TransactionAttributeSourcePointcut.matches() 因此不匹配([framework] spring-
tx/src/main/java/org/springframework/transaction/interceptor/TransactionAttributeSourcePointcut.java:54 ),advisor 根本不会织到这个⽅法上。

3.3 本基线的准确表述

参考⼿册是权威([framework] framework-docs/modules/ROOT/pages/data-access/transaction/declarative/annotations.adoc:173-180 ):

"The @Transactional annotation is typically used on methods with public visibility. As of 6.0, protected or package-visible methods can also be madetransactional for class-based proxies by default. Note that transactional methods in interface-based proxies must always be public and defined in theproxied interface."

"If you prefer consistent treatment of method visibility across the different kinds of proxies (which was the default up until 5.3), consider specifying
publicMethodsOnly "——随后给的示例正是注册⼀个 new AnnotationTransactionAttributeSource(true) 的 @Bean 。

所以本基线的准确表述是⼀张表,不是⼀句话:

⽅法可⻅性 CGLIB 代理(Boot 默认) JDK 接⼝代理 原因public ✅ ✅ (且必须声明在被代理接⼝上) —protected ✅ (6.0 起) ❌ ⼦类能覆写;接⼝上没这⽅法

package-private(同 ClassLoader) ✅ (6.0 起) ❌ 同上
package-private(跨 ClassLoader) ❌ ❌ ⻅下

private ❌ ❌ ⾮虚⽅法,⼦类⽆法覆写final ❌ ❌ ⽆法覆写static ❌ ❌ ⾮实例⽅法"Boot 默认 CGLIB"这⼀条也要坐实,它就在⾃动配置⾥明写着:

// [boot] module/spring-boot-transaction/src/main/java/org/springframework/boot/transaction/autoconfigure/TransactionAutoConfiguration.java:80-84

@Configuration(proxyBeanMethods = false)
@EnableTransactionManagement(proxyTargetClass = true)
@ConditionalOnBooleanProperty(name = "spring.aop.proxy-target-class", matchIfMissing = true)
static class CglibAutoProxyConfiguration {
}

matchIfMissing = true ——不配就是 CGLIB。所以在⼀个默认的 Boot 4 应⽤⾥, protected 上的 @Transactional 是⽣效的。

后三⾏的物理依据在校验⽅法⾥:

// [framework] spring-aop/src/main/java/org/springframework/aop/framework/CglibAopProxy.java:290-291

int mod = method.getModifiers();
if (!Modifier.isStatic(mod) && !Modifier.isPrivate(mod)) { // ← private/static直接跳过校验,压根不可能代理
if (Modifier.isFinal(mod)) { ... }
else if (logger.isDebugEnabled() && !Modifier.isPublic(mod) && !Modifier.isProtected(mod) &&
proxyClassLoader != null && proxySuperClass.getClassLoader() != proxyClassLoader) {
logger.debug("Method [" + method + "] is package-visible across different ClassLoaders " +
"and cannot get proxied via CGLIB: ..."); // :316-318
}
}

3.4 ⚠ ⼀处新形态的阴险:private 上的 @Transactionalprivate ⽅法在本基线下有个⽐ 5.3 时代更难查的表现。

5.3 时代: publicMethodsOnly = true , computeTransactionAttribute 在第⼀⾏就把 private ⽅法过滤掉,元数据直接不解析。
本基线: publicMethodsOnly = false ,那道 Modifier.isPublic 检查关掉了。⽽ pointcut 的类级筛选⾛的是 AopUtils.canApply ,它遍历的是
ReflectionUtils.getAllDeclaredMethods(clazz) ([framework] spring-aop/src/main/java/org/springframework/aop/support/AopUtils.java:263 )——

getDeclaredMethods 是包含 private ⽅法的。于是元数据被正常解析、pointcut 可能因这个 private ⽅法⽽判定"这个类要代理",但 CGLIB ⽣成的⼦类⽆论如何覆写不了private ⽅法,运⾏期依然拦不到。

元数据说"是事务⽅法",字节码说"我拦不到"。 注解看起来"被认了",⾏为却完全没有。

📌 诚实标注:此条是我基于两条源码路径( Modifier.isPublic 检查已关 + CGLIB ⽆法覆写 private)做的逻辑推演,没有跑最⼩复现验证。结论⽅向我有把握,但"pointcut 是否真的因此把整个类判为需代理"这⼀步我未实测,写进你⾃⼰的排查⼿册前建议补⼀个⽤例。

顺带说⼀句:private ⽅法即便能被拦截也没意义——private ⽅法只能被同类调⽤,⽽同类调⽤就是⾃调⽤。坑⼀和坑⼆在 private 这个点上会合了。

3.5 ⻣灰级:属性查找的四级回退,以及"完全覆盖"

AbstractFallbackTransactionAttributeSource 的类 javadoc 写明了顺序:1. specific target method → 2. target class → 3. declaring method → 4. declaring

class/interface,实现在 [framework] AbstractFallbackTransactionAttributeSource.java:171-200 ,第⼀步先⽤ AopUtils.getMostSpecificMethod(method,

targetClass) ( :173 )从接⼝⽅法定位到实现类上的真实⽅法。

⚠ 易错点:类 javadoc 的原话是 "Any transaction attribute associated with the target method completely overrides a class transaction attribute."——是完全覆盖,不是逐属

性合并。类上写了 @Transactional(readOnly = true) ,⽅法上写个光秃秃的 @Transactional , readOnly 就没了,不会继承。

四、坑三:默认不回滚受检异常4.1 全 Spring 最著名的默认值,实现只有⼀⾏// [framework] spring-tx/src/main/java/org/springframework/transaction/interceptor/DefaultTransactionAttribute.java:179-182@Override

public boolean rollbackOn(Throwable ex) {
return (ex instanceof RuntimeException || ex instanceof Error);
}

就这⼀⾏。

为什么这么设计——答案在它上⾯那段 javadoc([framework] DefaultTransactionAttribute.java:165-177 ),值得整段引:
"The default behavior is as with EJB: rollback on unchecked exception ( RuntimeException ), assuming an unexpected outcome outside any business rules.

Additionally, we also attempt to rollback on Error which is clearly an unexpected outcome as well. By contrast, a checked exception is considered a businessexception and therefore a regular expected outcome of the transactional business method, i.e. a kind of alternative return value which still allows for regularcompletion of resource operations."

"a kind of alternative return value"——受检异常是另⼀种返回值。 这是理解这个坑的钥匙:不是 Spring 偷懒,是它继承了⼀整套 EJB 的世界观。在那套世界观⾥, throwsInsufficientBalanceException 和 return Result.fail() 是同⼀类东⻄——业务上预期之内的分⽀,凭什么回滚?

RollbackOn 枚举的 javadoc 也把⾎统交代了:"the default behavior matches the traditional behavior in EJB CMT and JTA"([framework] spring-
tx/src/main/java/org/springframework/transaction/annotation/RollbackOn.java:22-23 )。

坑在哪:因为 Java 的受检异常在实践中早就沦为"被迫 throws 的噪⾳",⽽不是"精⼼设计的业务分⽀"。 IOException 、 SQLException 、 TimeoutException ——没有⼀个是"预期之内的另⼀种返回值"。⼀套 1998 年的世界观,遇上 2026 年的代码习惯。

4.2 规则仲裁:最浅者胜⼀旦你写了 rollbackFor / noRollbackFor ,⾛的就是另⼀个实现:

// [framework] spring-tx/src/main/java/org/springframework/transaction/interceptor/RuleBasedTransactionAttribute.java:116-123/**

* Winning rule is the shallowest rule (that is, the closest in the
* inheritance hierarchy to the exception). If no rule applies (-1),
* return {@code false}.

*/

@Override

public boolean rollbackOn(Throwable ex) {
RollbackRuleAttribute winner = null;
int deepest = Integer.MAX_VALUE;
if (this.rollbackRules != null) {
for (RollbackRuleAttribute rule : this.rollbackRules) {
int depth = rule.getDepth(ex);
if (depth >= 0 && depth < deepest) { deepest = depth; winner = rule; }
}
}
// User superclass behavior (rollback on unchecked) if no rule matches.
if (winner == null) {
return super.rollbackOn(ex); // ←退回上⾯那⼀⾏
}
return !(winner instanceof NoRollbackRuleAttribute);
}

三个要点: - rollbackFor 和 noRollbackFor 装进同⼀个 List,靠 NoRollbackRuleAttribute 这个⼦类型区分。设计上很⼲净。 - 不是"先来后到",是"继承树上离得近的

赢"。所以 rollbackFor = Exception.class, noRollbackFor = MyBizException.class ⾥, MyBizException 更浅,不回滚——符合直觉。 - ⼀条规则都没匹配 → 退回那

唯⼀的⼀⾏。

4.3 【本基线 · 6.2 起】全局开关,⽽且官⽅建议你打开这是很多资料没跟上的:

// [framework] spring-tx/src/main/java/org/springframework/transaction/annotation/EnableTransactionManagement.java:222

RollbackOn rollbackOn() default RollbackOn.RUNTIME_EXCEPTIONS;
javadoc ⾥给了 Spring 团队罕⻅地明确的态度([framework] EnableTransactionManagement.java:211-215 ):

"Unless you rely on EJB-style business exceptions with commit behavior, it is advisable to switch to RollbackOn.ALL_EXCEPTIONS for a consistent rollback

even in case of a (potentially accidental) checked exception. Also, it is advisable to make that switch for Kotlin-based applications where there is no

enforcement of checked exceptions at all."

Spring ⾃⼰在说:除⾮你真的在⽤ EJB 那套,否则应该切过去。 这⼏乎等于官⽅承认默认值已经不合时宜了——只是为了向后兼容不能改。

落地路径就是 §3.1 那段代码:读到 ALL_EXCEPTIONS 就调 tas.addDefaultRollbackRule(RollbackRuleAttribute.ROLLBACK_ON_ALL_EXCEPTIONS) ([framework]
AnnotationTransactionAttributeSource.java:159 ;常量在 [framework] RollbackRuleAttribute.java:74 , Exception.class )。

✨ 精妙在哪:它是"往规则表⾥加⼀条默认规则",不是"替换 rollbackOn ⽅法"。所以你⽅法上⾃⼰写的 noRollbackFor 依然按"最浅者胜"⽣效。javadoc 原话:"transaction-

specific rollback rules override the default behavior but retain the chosen default for unspecified exceptions."( EnableTransactionManagement.java:207-208 )。加⼀条

⽐换⼀套优雅。

⚠ ⼀处边界:这个开关"affects Spring's Transactional as well as jakarta.transaction.Transactional but leaves the non-rule-based

jakarta.ejb.TransactionAttribute as-is"([framework] RollbackOn.java:24-26 )。原因很物理:只有 RuleBasedTransactionAttribute 才有规则表可塞。

4.4 ⚠ 别⽤字符串规则

rollbackForClassName / noRollbackForClassName ⽤的是⼦串包含匹配,不是类型匹配。 @Transactional 的 javadoc 为此写了⼀段罕⻅的⻓警告([framework] spring-
tx/src/main/java/org/springframework/transaction/annotation/Transactional.java:76-92 ):

"...a thrown exception is considered to be a match for a given pattern-based rollback rule if the name of thrown exception contains the exception pattern. Forexample, given a rule configured to match against "com.example.CustomException" , that rule will match against an exception named

com.example.CustomExceptionV2 ... or an exception named com.example.CustomException$AnotherException (an exception declared as a nested class)."
rollbackForClassName = "CustomException" 会连带命中 CustomExceptionV2 和它所有内部类。写 "Exception" 更是"will match nearly anything and will probably

hide other rules"。

结论⼀句话:⽤ rollbackFor (Class),别⽤ rollbackForClassName (String)。 后者存在的唯⼀理由是"异常类在编译期不可⻅",这在绝⼤多数应⽤⾥根本不成⽴。

4.5 ⻣灰级:异常不⼀定要"抛出来"才算回滚判定的调⽤点在 [framework] spring-tx/src/main/java/org/springframework/transaction/interceptor/TransactionAspectSupport.java:705-706 。但还有两

条⼏乎没⼈知道的分⽀([framework] TransactionAspectSupport.java:382-406 ):
⽅法正常返回了⼀个已完成的 Future ,⽽ future.get() 抛 ExecutionException → 照样按 rollbackOn(cause) 判定并 setRollbackOnly() ;

返回 Vavr 的 Try 且是 Failure → 同上。

即"异常"包在返回值⾥也算。

另外注意 :721-722 那两⾏注释:

// We don't roll back on this exception.

// Will still roll back if TransactionStatus.isRollbackOnly() is true.

即使规则说"不回滚",只要 rollback-only 标记已经被打上,最终还是回滚。 这是第七节那个 UnexpectedRollbackException 的伏笔。

五、坑四:在 @PostConstruct ⾥⽤事务——壳还没⽣出来参考⼿册的判决很短:

"Also, the proxy must be fully initialized to provide the expected behavior, so you should not rely on this feature in your initialization code -- for example, in a@PostConstruct method." ——[framework] framework-docs/modules/ROOT/pages/data-access/transaction/declarative/annotations.adoc:222-224物理原因是⼀条时间线,三个坐标就钉死了:

// [framework] spring-beans/src/main/java/org/springframework/beans/factory/support/AbstractAutowireCapableBeanFactory.java:1797

protected Object initializeBean(String beanName, Object bean, @Nullable RootBeanDefinition mbd) {

...

invokeAwareMethods(beanName, bean); // :1803
Object wrappedBean = bean;
if (mbd == null || !mbd.isSynthetic()) {
wrappedBean = applyBeanPostProcessorsBeforeInitialization(wrappedBean, beanName); // :1807 ← @PostConstruct在这⾥跑
}
try {
invokeInitMethods(beanName, wrappedBean, mbd); // :1811 ← afterPropertiesSet / initMethod
}

...

if (mbd == null || !mbd.isSynthetic()) {
wrappedBean = applyBeanPostProcessorsAfterInitialization(wrappedBean, beanName); // :1818 ←壳在这⾥才诞⽣
}
return wrappedBean;
}
@PostConstruct 由 CommonAnnotationBeanPostProcessor 注册([framework] spring-

context/src/main/java/org/springframework/context/annotation/CommonAnnotationBeanPostProcessor.java:194 ,注册的是

jakarta.annotation.PostConstruct ——本基线全⾯ jakarta,零 javax),执⾏点是 postProcessBeforeInitialization ([framework] spring-
beans/src/main/java/org/springframework/beans/factory/annotation/InitDestroyAnnotationBeanPostProcessor.java:214 ),落在 :1807 。
壳由 AbstractAutoProxyCreator.postProcessAfterInitialization 造([framework] spring-
aop/src/main/java/org/springframework/aop/framework/autoproxy/AbstractAutoProxyCreator.java:285 ,内部调 wrapIfNecessary , :289 ),落在 :1818 。

1807 < 1818 。 @PostConstruct 执⾏的那⼀刻,包裹这个 bean 的壳在物理上还不存在。

于是两个独⽴原因叠加,失效得⾮常彻底:

1. 在 @PostConstruct ⾥调 this.someTransactionalMethod() → this ⼀定是原件本⼈( initializeBean 的返回值还没产⽣呢),这是坑⼀;
  1. @PostConstruct ⽅法本身标 @Transactional → 更彻底:调⽤它的是容器的 BPP,直接对着裸 bean 反射调过去,连"经过壳"的可能性都不存在。

✨ ⼀个反直觉的例外:如果你在 @PostConstruct ⾥调的是别的 bean 的事务⽅法,那是正常⼯作的——别的 bean 早就跑完了⾃⼰的 initializeBean ,你注⼊拿到的就是壳。

失效只针对"⾃⼰身上的事务"。

正确做法: - 挪到 @EventListener(ApplicationReadyEvent.class) 或 ContextRefreshedEvent ——此时全部 bean(含壳)都已就绪; - 或者⼲脆⽤
TransactionTemplate 。Boot 会⾃动配⼀个([boot] module/spring-boot-

transaction/src/main/java/org/springframework/boot/transaction/autoconfigure/TransactionAutoConfiguration.java:57-64 ,条件是

@ConditionalOnSingleCandidate(PlatformTransactionManager.class) + @ConditionalOnMissingBean(TransactionOperations.class) )。编程式事务不依赖壳

——这是它在这个场景下不可替代的优势。

🦴 余味:"壳⼀定在 :1818 才诞⽣"其实也不是铁板⼀块。循环依赖场景下, AbstractAutoProxyCreator.getEarlyBeanReference ([framework] :237-240 )会提前把壳

造出来,再靠 postProcessAfterInitialization ⾥的 if (this.earlyBeanReferences.remove(cacheKey) != bean) ( :287 )避免造第⼆次。规则之下还有例外——

但那是第 09 章循环依赖的地盘,这⾥点到为⽌。

六、坑五:多数据源与"选错事务管理器"——本章最难查的⼀个6.1 选管理器的决策链

// [framework] spring-tx/src/main/java/org/springframework/transaction/interceptor/TransactionAspectSupport.java:489 (@since 6.2)
protected @Nullable TransactionManager determineTransactionManager(
@Nullable TransactionAttribute txAttr, @Nullable Class<?> targetClass) {
TransactionManager tm = determineTransactionManager(txAttr); //单参版,已废弃
if (tm != null) return tm;
if (txAttr == null || this.beanFactory == null) return getTransactionManager();
String qualifier = txAttr.getQualifier(); // :502①注解上的 qualifier
if (StringUtils.hasText(qualifier)) {
return determineQualifiedTransactionManager(this.beanFactory, qualifier);
}
else if (targetClass != null) {
String typeQualifier = BeanFactoryAnnotationUtils.getQualifierValue(targetClass); // :508②类级 @Qualifier
if (StringUtils.hasText(typeQualifier)) {
try {
return determineQualifiedTransactionManager(this.beanFactory, typeQualifier);
}
catch (NoSuchBeanDefinitionException ex) {

// Consider type qualifier as optional, proceed with regular resolution below. // :514

}
}
}
if (StringUtils.hasText(this.transactionManagerBeanName)) { // :519③配置的默认 bean名
return determineQualifiedTransactionManager(this.beanFactory, this.transactionManagerBeanName);
}
else {
TransactionManager defaultTransactionManager = getTransactionManager(); // :523④显式注⼊的 tm
if (defaultTransactionManager == null) {
defaultTransactionManager = this.transactionManagerCache.get(DEFAULT_TRANSACTION_MANAGER_KEY);
if (defaultTransactionManager == null) {
defaultTransactionManager = this.beanFactory.getBean(TransactionManager.class); // :527⑤按类型兜底

...

}
}
return defaultTransactionManager;
}
}
优先级清清楚楚: @Transactional("xxx") → 类级 @Qualifier → transactionManagerBeanName → 显式注⼊的 tm → 按类型兜底。

⚠ 暗礁⼀(极其阴险): :513-515 那个 catch (NoSuchBeanDefinitionException) 是静默吞掉的。类上写了 @Qualifier("order") 但打错了字?不报错,不告警,悄悄退回去

⽤默认 tm。 你的事务会"⽣效",只是绑在了另⼀个数据源上。

⚠ 暗礁⼆: :527 的按类型兜底,如果容器⾥有两个 TransactionManager 且都没 @Primary ,这⾏会抛 NoUniqueBeanDefinitionException ——⽽且是在第⼀次调⽤事务⽅

法时才抛,不是启动时。启动⼀切正常,流量⼀来才炸。

📌 【本基线纠偏】 单参版 determineTransactionManager(TransactionAttribute) 已被 @Deprecated(since = "6.2") ,⽽且基类实现直接返回 null([framework]

TransactionAspectSupport.java:538-543 )。⽼资料⾥"重写 determineTransactionManager 来做多数据源路由"的做法,在本基线下要改成重写双参版。

6.2 【本基线 · Boot 4】⾃动配置⾥的三条硬事实先说路径——Boot 4 做过明显的⽬录重组,⽼包名全部作废:

内容 Boot 3 时代常⻅包名 本基线实测事务⾃动配置 org.springframework.boot.autoconfigure.transaction org.springframework.boot.transaction.autoconfigure ,在独⽴模块 module/spring-boot-transactionJDBC 事务管理器 ...autoconfigure.jdbc org.springframework.boot.jdbc.autoconfigure ,在 module/spring-boot-jdbc

内容 Boot 3 时代常⻅包名 本基线实测AOP ⾃动配置 同名 包名未变: org.springframework.boot.autoconfigure.aop ,在 core/spring-boot-autoconfigure

事务模块的⾃动配置清单只有三⾏([boot] module/spring-boot-transaction/src/main/resources/META-
INF/spring/org.springframework.boot.autoconfigure.AutoConfiguration.imports )。

// [boot] module/spring-boot-jdbc/src/main/java/org/springframework/boot/jdbc/autoconfigure/DataSourceTransactionManagerAutoConfiguration.java:55-72

@Configuration(proxyBeanMethods = false)
@ConditionalOnSingleCandidate(DataSource.class) // :56 ←只有"唯⼀候选 DataSource"才⽣效
static class JdbcTransactionManagerConfiguration {

@Bean

@ConditionalOnMissingBean(TransactionManager.class) // :60
DataSourceTransactionManager transactionManager(Environment environment, DataSource dataSource,
ObjectProvider<TransactionManagerCustomizers> transactionManagerCustomizers) { ... }
private DataSourceTransactionManager createTransactionManager(Environment environment, DataSource dataSource) {
return environment.getProperty("spring.dao.exceptiontranslation.enabled", Boolean.class, Boolean.TRUE) // :69
? new JdbcTransactionManager(dataSource) : new DataSourceTransactionManager(dataSource); // :70
}
}

事实⼀:配了两个 DataSource 且都不带 @Primary → @ConditionalOnSingleCandidate 不满⾜ → Boot ⼀个事务管理器都不给你⾃动配。 然后 @Transactional 在第⼀次调⽤时炸在 TransactionAspectSupport.java:527 。多数据源必须⾃⼰声明 tm——这是设计,不是 bug。

事实⼆(纠偏):默认 tm 的实际类型是 JdbcTransactionManager ,不是 DataSourceTransactionManager 。 ⻅ :69-70 , spring.dao.exceptiontranslation.enabled 默

认 Boolean.TRUE 。很多资料还在说"Boot ⾃动配 DataSourceTransactionManager ",本基线下不准确。

事实三:JPA 在场时谁赢? [boot] module/spring-boot-jpa/src/main/java/org/springframework/boot/jpa/autoconfigure/JpaBaseConfiguration.java:100-103 的

transactionManager() 也带 @ConditionalOnMissingBean(TransactionManager.class) ,⽽ JDBC 那侧标了 @AutoConfigureOrder(Ordered.LOWEST_PRECEDENCE)
([boot] DataSourceTransactionManagerAutoConfiguration.java:52 )—— JpaTransactionManager 先落地,JDBC 让位。这个让位是对的:⽤了 JPA 却配

DataSourceTransactionManager , JdbcTemplate 和 EntityManager 会拿到两条不同的连接,事务形同虚设。

6.3 为什么"选错 tm"会 100% 静默物理机制只有⼀⾏:事务管理器把连接绑在⼀条挂在本⼈身上的绳上(ThreadLocal),⽽ JdbcTemplate 取连接时,⽤ DataSource 实例本身做 key 去查:

// [framework] spring-jdbc/src/main/java/org/springframework/jdbc/datasource/DataSourceUtils.java:106

ConnectionHolder conHolder = (ConnectionHolder) TransactionSynchronizationManager.getResource(dataSource);

于是:tm 绑的是 dataSourceA ,你的 JdbcTemplate ⽤的是 dataSourceB → getResource 返回 null → 从池⾥新拿⼀条 autoCommit 的连接 → SQL 照常执⾏、照常成功、事务完全不起作⽤,⼀⾏报错都没有。

排查抓⼿: TransactionSynchronizationManager.isActualTransactionActive() 返回 true(事务确实开了),但 getResource(yourDataSource) 返回 null(只是没绑到你⽤

的那个源上)。这两个值同时看,⼀秒定位。

参考⼿册把这个列为"常⻅问题"的第⼀条([framework] framework-docs/modules/ROOT/pages/data-access/transaction/solutions-to-common-problems.adoc ),⽤词很

重:本地事务在这种场合 "do not make sense, and a good application server treats them as errors"。

🦴 顺带⼀条:Boot 4 的 JTA ⽀持缩⽔了。 [boot] module/spring-boot-

transaction/src/main/java/org/springframework/boot/transaction/jta/autoconfigure/JtaAutoConfiguration.java:38-39 只@Import(JndiJtaConfiguration.class) ,整个包下只有三个⽂件。也就是说 Boot 4 不再帮你内嵌 XA 事务管理器,要么跑在应⽤服务器⾥查 JNDI,要么⾃⼰搭。

spring.jta.enabled 默认 true( matchIfMissing = true ),但"默认开启"开的只是 JNDI 这⼀条路。 这对"多数据源要不要上 XA"这个⾼频问题给出了框架的态度:别上。

⽤最终⼀致性。

七、坑六:事务⾥发消息、调远程——三个层次的问题这是六个坑⾥唯⼀⼀个不是 Spring 的错的坑,但它最贵。

层次⼀:事务在物理上包不住外部世界。 数据库回滚了,HTTP 请求收不回来,MQ 消息撤不回来。这是分布式的本质。

层次⼆:⻓事务。 远程调⽤把 DB 连接和⾏锁攥在⼿⾥,持有时间从毫秒变成秒,甚⾄超时级。压测才暴露,线上才致命。

层次三:时序错位(最常⻅的具体 bug)。 事务⾥ insert 之后⽴刻发 MQ,消费者收到消息去查库——查不到。因为发消息时事务还没提交。经典的"消息⽐数据快"。

7.1 底层钩⼦: TransactionSynchronization// [framework] spring-tx/src/main/java/org/springframework/transaction/support/TransactionSynchronizationManager.java:333

public static void registerSynchronization(TransactionSynchronization synchronization) throws IllegalStateException {
Assert.notNull(synchronization, "TransactionSynchronization must not be null");
Set<TransactionSynchronization> synchs = synchronizations.get();
if (synchs == null) {
throw new IllegalStateException("Transaction synchronization is not active"); // :339 ←没事务就抛
}
synchs.add(synchronization);
}
四个回调,⾏为差异很⼤([framework] spring-tx/src/main/java/org/springframework/transaction/support/TransactionSynchronization.java ):

回调 ⾏号 抛异常会怎样

beforeCommit(boolean readOnly) :133 传播给调⽤⽅,并导致回滚
beforeCompletion() :147 只记⽇志,不传播;commit / rollback 都会⾛
afterCommit() :165 传播给调⽤⽅
afterCompletion(int status) :186 只记⽇志,不传播
afterCommit 的那段 javadoc 是本章最该整段引⽤的⼀处([framework] TransactionSynchronization.java:150-161 ):

"Can, for example, commit further operations that are supposed to follow on a successful commit of the main transaction, like confirmation messages or emails."

"NOTE: The transaction will have been committed already, but the transactional resources might still be active and accessible. As a consequence, any data

access code triggered at this point will still "participate" in the original transaction, allowing to perform some cleanup (with no commit following anymore!)...

Hence: Use PROPAGATION_REQUIRES_NEW for any transactional operation that is called from here."

这⼀段⾥精妙和暗礁挤在⼀起:

✨ 精妙:框架给了你⼀个"提交成功之后"的确定性钩⼦,⽽且 javadoc ⾥点名了它的⽤例就是"确认消息 / 邮件"。这正是层次三那个坑的标准答案。

⚠ 暗礁:这个钩⼦⾥写库会静默丢失。 连接还绑在绳上,你的 insert 会加⼊那个已经提交完、不会再提交的事务,然后随着连接归还被丢掉。不报错,数据没了。

我给这扇⻔起个名字:提交之后的那扇⻔,只出不进。 往外发消息可以,往⾥写库不⾏——除⾮你⾃⼰开⼀个新事务。

7.2 上层封装: @TransactionalEventListener (推荐,但有三个默认值必须知道)

⽇常⽤不要直接写 TransactionSynchronization ,⽤注解。但有三个默认值必须回源核过:

默认值⼀: phase() 默认是 AFTER_COMMIT 。 [framework] spring-

tx/src/main/java/org/springframework/transaction/event/TransactionalEventListener.java:78 。

默认值⼆: fallbackExecution() 默认 false ——这是个巨坑。 [framework] TransactionalEventListener.java:110 。类 javadoc 说得很直⽩:

"If the event is not published within an active transaction, the event is discarded unless the fallbackExecution flag is explicitly set." ——[framework]TransactionalEventListener.java:32-33

⚠ 同⼀个 publishEvent 调⽤,在事务⾥会被处理,不在事务⾥默默丢弃,⽆任何⽇志。 写单测时"事务外调⽤ → 监听器没触发",⼗有⼋九是这条。

⽽且这⾥有个特别容易搞混的细节: fallbackExecution 是 @AliasFor(annotation = EventListener.class, attribute = "defaultExecution") ([framework]
TransactionalEventListener.java:109 ),⽽ EventListener#defaultExecution() 的默认值是 true ([framework] spring-
context/src/main/java/org/springframework/context/event/EventListener.java:140 )。两个默认值⽅向相反—— @TransactionalEventListener 把它翻转成了

false。别写混。

默认值三(最反直觉): AFTER_COMMIT ⾛的不是 afterCommit() ,是 afterCompletion() 。
" AFTER_COMMIT — ... Note: This is a specialization of AFTER_COMPLETION and therefore executes in the same sequence of events as AFTER_COMPLETION (and
not in TransactionSynchronization.afterCommit() ). Interactions with the underlying transactional resource will not be committed in this phase." ——

[framework] spring-tx/src/main/java/org/springframework/transaction/event/TransactionPhase.java:42-49

类 javadoc 的 WARNING 把结论说死([framework] TransactionalEventListener.java:48-57 ):"...any data access code triggered at this point will still "participate" in

the original transaction, but changes will not be committed to the transactional resource."

所以本章最实⽤的⼀条落地纪律是:

@TransactionalEventListener 的⽅法⾥如果要写库,必须再套⼀层 @Transactional(propagation = Propagation.REQUIRES_NEW) 。 ⽽且——因为

REQUIRES_NEW 是另⼀件器上的事务,这个监听器⽅法不能和发布事件的⽅法在同⼀个类⾥,否则你⼜掉回坑⼀。

(⼯⼚类是 RestrictedTransactionalEventListenerFactory ,由 @EnableTransactionManagement ⾃动注册,⻅ [framework]
AbstractTransactionManagementConfiguration.java:97 。)

7.3 附带的第七个坑: UnexpectedRollbackException这个坑和坑六同源(都是"事务边界与业务边界错位"),⽽且极其⾼频。

场景:外层 @Transactional 调内层 @Transactional (默认 REQUIRED ,参与同⼀个物理事务),内层抛异常,外层 try-catch 吞掉、正常 return → 外层提交时抛UnexpectedRollbackException 。

三段代码串起来:

① 内层回滚时,因为它不是新事务、只是"participating",于是打全局回滚标记:

// [framework] spring-tx/src/main/java/org/springframework/transaction/support/AbstractPlatformTransactionManager.java:898-905

else {

// Participating in larger transaction

if (status.hasTransaction()) {
if (status.isLocalRollbackOnly() || isGlobalRollbackOnParticipationFailure()) {
logger.debug("Participating transaction failed - marking existing transaction as rollback-only");
doSetRollbackOnly(status);
}
② 这个开关默认 true([framework] AbstractPlatformTransactionManager.java:138 ),javadoc 措辞不留余地( :258-262 ):

"Default is 'true': ... The only possible outcome of such a transaction is a rollback: The transaction originatorcannot make the transaction commit anymore."

③ 外层 commit 时发现标记([framework] :749 ),转去 processRollback ,末尾抛出([framework] :935-938 ):

// Raise UnexpectedRollbackException if we had a global rollback-only marker

if (unexpectedRollback) {
throw new UnexpectedRollbackException(
"Transaction rolled back because it has been marked as rollback-only");
}

🦴 ⻣灰级细节:仓⾥还有⼀条措辞不同的相邻消息——[framework] AbstractPlatformTransactionManager.java:803-804 的 "Transaction silently rolled back

because it has been marked as rollback-only" ,⾛的是 processCommit ⾥"提交本身没报错但标记在"的另⼀条路径。两条⽂案不同,搜⽇志时别搜错。

另外,默认只在最外层抛: failEarlyOnGlobalRollbackOnly 默认 false ([framework] :140 )。
解法——框架⾃⼰给了官⽅答案([framework] AbstractPlatformTransactionManager.java:278-283 ):
"The recommended solution for handling failure of a subtransaction is a "nested transaction"... PROPAGATION_NESTED provides exactly those semantics;

however, it will only work when nested transaction support is available. This is the case with DataSourceTransactionManager , but not withJtaTransactionManager ."

三条路,我的排序: 1. 外层别 try-catch 吞异常——最简单,⽽且通常最正确。你吞掉的是"数据已经不⼀致了"这个事实。 2. 内层 REQUIRES_NEW ——独⽴物理事务,失败不污染外层。代价是真的独⽴提交:外层回滚时内层不会跟着回滚。 3. 内层 NESTED (savepoint)——语义最贴合"局部失败可回退",但 JTA 不⽀持。

7.4 【本基线 · 7.0.3 新增】终于能观测回滚了这是 Framework 7 的新东⻄,⽼资料完全没有:

// [framework] spring-tx/src/main/java/org/springframework/transaction/interceptor/MethodRollbackEvent.java:42 (@since 7.0.3,⻅ :35)
public class MethodRollbackEvent extends MethodFailureEvent {
private final TransactionExecution transaction;

...

}
发布点在 TransactionInterceptor ⾥——它现在实现了 ApplicationEventPublisherAware ([framework] TransactionInterceptor.java:59 ):

// [framework] spring-tx/src/main/java/org/springframework/transaction/interceptor/TransactionInterceptor.java:136-148@Override

public void onRollback(Throwable failure, TransactionExecution execution) {
MethodRollbackEvent event = new MethodRollbackEvent(invocation, failure, execution);
logger.trace(event, failure);
if (applicationEventPublisher != null) {
try {
applicationEventPublisher.publishEvent(event);
}
catch (Throwable ex) {
if (logger.isWarnEnabled()) {
logger.warn("Failed to publish " + event, ex);
}
}
}
}
调⽤点在 TransactionAspectSupport.java:706 ——在真正 rollback() 之前。javadoc 确认:"This event gets published rightbefore the actual transaction rollback."

价值:解决了⼀个⻓期痛点——"哪些⽅法在回滚?多久回滚⼀次?"以前只能靠⽇志或者⾃⼰写切⾯,现在框架直接给事件,接个监听器就能出指标。

⚠ 但要清醒两点:⼀,Spring 事件默认是同步⼴播, publishEvent 在当前线程跑完所有监听器,所以监听器⾥⼲重活会拖慢回滚路径;⼆,它被 try-catch 兜住了,监听器抛异常只

warn ,不影响回滚本身——这个设计是对的(观测不该⼲扰主链路),但也意味着你的监控代码坏了会静默。

7.5 顺带:绳⼦不跨线程// [framework] spring-tx/src/main/java/org/springframework/transaction/annotation/Transactional.java:100-103"This annotation commonly works with thread-bound transactions ... exposing a transaction to alldata access operations within the current execution thread.Note: This does NOT propagate to newly started threads within the method."

@Transactional ⽅法⾥ CompletableFuture.runAsync(...) 或调 @Async ⽅法,新线程⾥完全没有事务。绳⼦挂在本⼈身上,换了⼈就断。同理, @Async +@Transactional 叠在同⼀个⽅法上,事务是在异步线程⾥独⽴开的,和调⽤⽅毫⽆关系。

🦴 ⻣灰级细节

1. Spring 的 CGLIB 代理从不调 super 。 intercept 的 methodProxy 参数被完全忽略([framework] CglibAopProxy.java:715 ),⾛的是

targetSource.getTarget() + 反射。这是"代理是空壳"这个模型的字节码级证据。

  1. AopContext.setCurrentProxy 是包级私有([framework] AopContext.java:84 ),全仓只有三处能塞值。框架把逃⽣舱的⻔把⼿焊在了⾃⼰家⾥。
  1. "⽅法上的 @Transactional 完全覆盖类上的"——是完全覆盖,不是逐属性合并。类上的 readOnly = true 会被⽅法上⼀个光秃秃的 @Transactional 抹掉。
4. 回滚判定不只看抛出的异常:⽅法正常返回⼀个失败的 Future 或 Vavr Try ,⼀样按 rollbackOn(cause) 判定([framework] TransactionAspectSupport.java:382-
406 )。
  1. 两条 UnexpectedRollbackException ⽂案: :937-938 的 "Transaction rolled back..." 和 :803-804 的 "Transaction silently rolled back..." ,来⾃两条不同路径。

⚠ 暗礁清单

类级 @Qualifier 打错字不报错([framework] TransactionAspectSupport.java:513-515 静默 catch ),悄悄退回默认 tm。
两个 TransactionManager 都没 @Primary ,炸在第⼀次调⽤⽽不是启动时([framework] :527 )。
@TransactionalEventListener 在事务外发布 → 事件被丢弃,零⽇志([framework] TransactionalEventListener.java:32-33 , fallbackExecution 默认
false )。

AFTER_COMMIT 阶段⾥写库 → 静默丢失,必须 REQUIRES_NEW 。

rollbackForClassName 是⼦串包含匹配, "CustomException" 会连带命中 CustomExceptionV2 。

选错 DataSource 对应的 tm → 100% 静默:SQL 成功、事务不⽣效、零报错。抓⼿是 isActualTransactionActive() 为 true 但 getResource(ds) 为 null。

🎯 三句带⾛1. @Transactional 只拦从代理外⾯进来的调⽤;同类 this. ⾃调⽤、 @PostConstruct 、 private / final / static ⽅法⼀律拦不到——不报错、不告警,只是不⽣效。

2. 本基线的两个纠偏: @EnableTransactionManagement 显式传 publicMethodsOnly=false ([framework]
AbstractTransactionManagementConfiguration.java:86 ),CGLIB 下 protected /包级⽅法有效(6.0 起);Boot 4 默认⾃动配的是 JdbcTransactionManager 不是
DataSourceTransactionManager ([boot] DataSourceTransactionManagerAutoConfiguration.java:69-70 )。
3. 默认只回滚 RuntimeException / Error ([framework] DefaultTransactionAttribute.java:180-181 );要发消息就⽤ @TransactionalEventListener (默认

AFTER_COMMIT ),⾥⾯写库必须 REQUIRES_NEW ,且监听器要放在另⼀个 bean ⾥。

承上启下这⼀章从头到尾在讲同⼀件事:你以为你在使唤原件,其实每次都得先过壳——⽽壳只在⻔⼝站着。 站在⻔⼝,就意味着它拦得住敲⻔的⼈,拦不住已经在屋⾥的⼈。

我们已经把这道⻔⾥外都翻了个遍。可有⼀个问题⼀直没问:最外⾯那道⻔,是谁开的?

⼀次 HTTP 请求打进来,它先落在哪⾥?谁决定"这⼀单该谁接"?那个把请求变成⼀次⽅法调⽤、最终敲响某个壳的⻆⾊——它⾃⼰⻓什么样?

下⼀章,我们回到坊⾥最热闹的地⽅:⻔市的柜台。所有客都从这⼀个⼝进,所有单都在这⾥被分派。我们跟着⼀个请求,看 DispatcherServlet 的⼀次完整派发——从它接住请求的那⼀刻,到它把响应写回去为⽌,中间到底站了多少个⼈。