@PostConstruct 方法上的 @Transactional [英] @Transactional on @PostConstruct method

查看:44
本文介绍了@PostConstruct 方法上的 @Transactional的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在我的应用程序开始时读取文本数据固定装置(CSV 文件)并将其放入我的数据库中.

I want to read text data fixtures (CSV files) at the start on my application and put it in my database.

为此,我创建了一个带有初始化方法(@PostConstruct 注释)的 PopulationService.

For that, I have created a PopulationService with an initialization method (@PostConstruct annotation).

我还希望它们在单个事务中执行,因此我在同一方法中添加了 @Transactional.

I also want them to be executed in a single transaction, and hence I added @Transactional on the same method.

然而,@Transactional 似乎被忽略了:事务在我的低级 DAO 方法中启动/停止.

However, the @Transactional seems to be ignored : The transaction is started / stopped at my low level DAO methods.

那我需要手动管理交易吗?

Do I need to manage the transaction manually then ?

推荐答案

引自遗留(已关闭)Spring 论坛:

Quote from legacy (closed) Spring forum:

在@PostConstruct 中(就像来自 InitializingBean 接口的 afterPropertiesSet),没有办法确保所有的后处理都已经完成,所以(确实)没有事务.确保它正常工作的唯一方法是使用 TransactionTemplate.

In the @PostConstruct (as with the afterPropertiesSet from the InitializingBean interface) there is no way to ensure that all the post processing is already done, so (indeed) there can be no Transactions. The only way to ensure that that is working is by using a TransactionTemplate.

因此,如果您希望在事务中执行 @PostConstruct 中的某些内容,则必须执行以下操作:

So if you would like something in your @PostConstruct to be executed within transaction you have to do something like this:

@Service("something")
public class Something {
    
    @Autowired
    @Qualifier("transactionManager")
    protected PlatformTransactionManager txManager;

    @PostConstruct
    private void init(){
        TransactionTemplate tmpl = new TransactionTemplate(txManager);
        tmpl.execute(new TransactionCallbackWithoutResult() {
            @Override
            protected void doInTransactionWithoutResult(TransactionStatus status) {
                //PUT YOUR CALL TO SERVICE HERE
            }
        });
   }
}

这篇关于@PostConstruct 方法上的 @Transactional的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆