gpt4 book ai didi

spring 事务管理 Propagation.REQUIRES_NEW 不起作用

转载 作者:行者123 更新时间:2023-12-02 09:37:35 26 4
gpt4 key购买 nike

我的服务等级。

@Service
@Transactional(value = "transactionManager", readOnly = true, propagation = Propagation.REQUIRED)
public class DeviceServiceImpl{

@Transactional(readOnly = false)
public void blockAllDevices(){

createSmsDeviceBlock();

}


public void createSmsDeviceBlock(){

addToLogTables();

smsService.sendSms();
}


@Transactional(readOnly = false,propagation = Propagation.REQUIRES_NEW)
public void addToLogTables(){
try {
//save object with DAO methods...
} catch (Exception e) {
throw new ServiceException(ServiceException.PROCESSING_FAILED, e.getMessage(), e);
}
}

}

从我的 Controller 中,调用了服务方法 blockAllDevices() 。addToLogTables() 方法被标记为 Propergation.REQUIRED_NEW,但问题在于 addToLogTables() 方法新事务未创建,而现有事务正在使用。

我想做的是,addToLogTables()方法上的事务应该在执行smsService.sendSms()方法之前提交。

我的问题是,如果事务提交失败,在方法 addToLogTables() 方法上,它不应该执行 smsService.sendSms() 方法。

最佳答案

这不是一个 Propagation.REQUIRES_NEW 问题。这是@Transactional 代理如何工作的问题。

当 Spring 代理使用 @Transactional 注解的 bean 时,它基本上将其包装在代理对象中,并在打开事务后将其委托(delegate)给它。当委托(delegate)调用返回时,代理会提交或回滚事务。

例如,您的 bean 是

@Autowired
private DeviceServiceImpl deviceService;

Spring 实际上会注入(inject)一个包装代理。

所以当你这样做时

deviceService.blockAllDevices();

您正在调用具有事务行为的代理上的方法。但是,在 blockAllDevices() 中,您正在执行

createSmsDeviceBlock();

这实际上是

this.createSmsDeviceBlock();

其中 this 指的是实际对象,而不是代理,因此不存在事务行为。

这在 documentation 中有进一步解释。 .

您必须重新设计您的设计。

关于spring 事务管理 Propagation.REQUIRES_NEW 不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21407918/

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