1.背景
查了一下Spring文档,就是上面这段话所说的情况。
2.Spring官方文档有这么一段话
https://docs.spring.io/spring-framework/docs/current/reference/html/data-access.html#transaction-declarative
In proxy mode (which is the default), only external method calls coming in through the proxy are intercepted. This means that self-invocation (in effect, a method within the target object calling another method of the target object) does not lead to an actual transaction at runtime even if the invoked method is marked with @Transactional. 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. |
我有一个Service类,
有一个方法会被当前类之外的类调用,称之为“A方法”,
A方法调用同一个类的另一个方法,称之为“B方法”,@Transactional注解加在B方法上面,
再来看官方文档的这句话,only external method calls coming in through the proxy are intercepted. 在这个例子中,A方法和B方法属于同一个类,同一个类的两个方法之间的调用,并没有“coming in through the proxy”,没有穿过Spring的动态代理。这样就根本没有形成Spring事务。
另外一个类的方法调用A方法,跨越了两个类,这样才是穿过了Spring的动态代理。
因此这里必须把@Transactional注解写在A方法上面。我这样修改了之后,事务就会回滚了,验证了Spring官方文档的这段话是正确的。