gpt4 book ai didi

java - Spring @Transactional 继承规则

转载 作者:IT老高 更新时间:2023-10-28 13:54:01 26 4
gpt4 key购买 nike

我有一组从抽象类继承核心功能的 @Service bean。我用 @Service@Transactional 标记了每个具体的子类服务。抽象父类(super class)包含每个服务的公共(public)入口点方法。换句话说,我有类似以下的内容:

abstract class AbstractService {

public void process() {
// Do common initialisation code here
processSpecific();
// Do common completion code here
}

abstract protected void processSpecific();
}


@Service @Transactional
public class FirstSpecificService extends AbstractService {
protected void processSpecific() {
// Do specific processing code here
}
}


@Service @Transactional
public class SecondSpecificService extends AbstractService {
protected void processSpecific() {
// Do different specific processing code here
}
}

每个具体子类服务中的具体代码多次调用DAO层对数据库进行更改,其中REQUIRED为事务传播类型。

现在有了上面定义的服务,我发现在这些具体的子类服务的任何代码中都没有当前事务,每次对 DAO 层的调用都在创建一个新事务,进行更改,提交交易并返回。

但是,如果我用@Transactional注释抽象父类(super class),那么一个事务正确创建的,并且对DAO层的子调用都参与当前交易。

所以我的问题是,继承 @Transactional 行为的规则是什么?为什么 Spring 不在它实际实例化的具体子类服务上使用 @Transactional ?在这种情况下,@Transactional 是否需要在父类(super class)上,因为那是公共(public)入口点方法所在的位置?

最佳答案

来自 spring 交易文档,

Note: In proxy mode (which is the default), only 'external' method calls coming in through the proxy will be intercepted. This means that 'self-invocation', i.e. a method within the target object calling some other method of the target object, won't lead to an actual transaction at runtime even if the invoked method is marked with @Transactional!

即使您在具体实现中有 @Transactional 并且您正在调用实际上是由您的注释进行事务处理的流程方法,但是由于此内部调用,在您的子类上调用 processSpecific 的流程方法不是事务性的。

研究编织。

关于java - Spring @Transactional 继承规则,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9918594/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com