相信你在 Spring 中掉入了 AOP 的陷阱。
Spring 中的事务是通过 AOP 实现的,而 Spring 中的 AOP 是通过围绕实际目标的代理来实现的。
您已经为 MyBean 注释了 @Transactional。假设其他人正在调用 的实例MyBean.test(),它实际上并没有直接与该对象“交谈”。有一个代理,看起来完全一样MyBean,但它创建事务,然后调用实际的MyBean.test(),然后是提交/回滚。
它是这样的:
test() test()
[Caller] -------> [MyBean Proxy] ------> [MyBean]
但是,当您调用test1()in时test(),这实际上意味着this.test1(),这意味着您正在直接调用 MyBean 实例:
[MyBean Proxy] [MyBean] <--
| | test1(c)
---------
如果不通过MyBean Proxy(负责执行事务技巧),您的调用test1()实际上与事务无关。这只是一个简单的方法。
所以你知道答案了。
Moreover, even you manage to invoke through the proxy, it is not going to change the story:
-> [MyBean Proxy] [MyBean]
test1(c) | |
-------------------------
That's because the instance of Car you passed to test1() is retrieved in the transaction (that means, Hibernate session) around test(), and whatever you change in test1(), you are not doing anything with the Hibernate session you created separately in test1() (if you use REQUIRED_NEW propagation). You are simply changing the state of the object passed in. Therefore, calling test1(c) is still nothing but a plain method call.