如何将Spring事务传播到另一个线程? [英] How to propagate Spring transaction to another thread?

查看:1657
本文介绍了如何将Spring事务传播到另一个线程?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

也许,我做错了什么,但我找不到适合下列情况的好办法。

Perhaps, I am doing something wrong, but I can't find a good way out for the following situation.

我想对一项服务进行单元测试使用下面的 Spring Batch 来执行作业。作业通过预先配置的 AsyncTaskExecutor 在单独的线程中执行。在我的单元测试中,我想:

I would like to unit test a service that uses Spring Batch underneath to execute jobs. The jobs are executed via pre-configured AsyncTaskExecutor in separate threads. In my unit test I would like to:


  1. 创建几个域对象并通过DAO保留它们

  2. 调用服务方法以启动作业

  3. 等待作业完成

  4. 使用DAO检索域对象并检查其状态

  1. Create few domain objects and persist them via DAO
  2. Invoke the service method to launch the job
  3. Wait until the job is completed
  4. Use DAO to retrieve domain objects and check their state

显然,以上所有内容都应在一次交易中执行,但不幸的是,交易没有传播到新线程(我理解这背后的理由)。

Obviously, all above should be executed within one transaction, but unfortunately, transactions are not propagated to new threads (I understand the rationale behind this).

我想到的想法:


  • 在步骤(1)之后提交交易#1。不好,因为在单元测试后应该回滚数据库状态。

  • 在作业配置中使用 Isolation.READ_UNCOMMITTED 。但这需要两种不同的测试和生产配置。

  • Commit the transaction#1 after step (1). Is not good, as the DB state should be rolled back after the unit test.
  • Use Isolation.READ_UNCOMMITTED in job configuration. But this requires two different configurations for test and for production.

推荐答案

我认为最简单的解决方案将在测试执行期间使用SyncTaskExecutor配置JobLauncher - 这样作业在与测试相同的线程中执行并共享事务。

I think the simplest solution would be configure the JobLauncher with a SyncTaskExecutor during test execution - this way the job is executed in the same thread as the test and shares the transaction.

任务执行器配置可以被移动到一个单独的弹簧配置xml文件。有两个版本 - 一个是在测试期间使用的SyncTaskExecutor,另一个是用于生产运行的AsyncTaskExecutor。

The task executor configuration can be moved to a separate spring configuration xml file. Have two versions of it - one with SyncTaskExecutor which is used during testing and the other AsyncTaskExecutor that is used for production runs.

这篇关于如何将Spring事务传播到另一个线程?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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