我正在使用 Spring Batch 和 JPA,并且经历了 TransactionManager bean 冲突。我通过在步骤中将 TransactionManager 设置为 JpaTransactionManager 找到了解决方案。但根据这个链接(https://github.com/spring-projects/spring-batch/issues/961 https://github.com/spring-projects/spring-batch/issues/961),尽管它对我有用,但它是不正确的。
@Autowired
private JpaTransactionManager transactionManager;
private Step buildTaskletStep() {
return stepBuilderFactory.get("SendCampaignStep")
.<UserAccount, UserAccount>chunk(pushServiceConfiguration.getCampaignBatchSize())
.reader(userAccountItemReader)
.processor(userAccountItemProcessor)
.writer(userAccountItemWriter)
.transactionManager(transactionManager)
.build();
}
}
我尝试了实现 BatchConfigurer 的建议解决方案,但它与我使用以下代码禁用元数据表相冲突:
@Configuration
@EnableAutoConfiguration
@EnableBatchProcessing
public class BatchConfiguration extends DefaultBatchConfigurer {
@Override
public void setDataSource(DataSource dataSource) {
// override to do not set datasource even if a datasource exist.
// initialize will use a Map based JobRepository (instead of database)
}
}
使用在步骤中设置 TransactionManager 的第一个解决方案会出现什么问题?
在 Spring Batch 中,有两个地方使用事务管理器:
- 在围绕创建的代理中
JobRepository
在与作业存储库交互时创建事务方法
- 在每个步骤定义中驱动步骤的事务
通常,两个地方都使用相同的事务管理器,但这不是必需的。使用a是完全可以的ResourcelessTransactionManager
作业存储库不存储任何元数据和JpaTransactionManager
在将数据保存到数据库的步骤中。
默认情况下,当您使用@EnableBatchProcessing
你提供一个DataSource
bean,Spring Batch 将创建一个DataSourceTransactionManager
并在两个地方都设置,因为这是最典型的情况。但没有什么可以阻止您在该步骤中使用不同的事务管理器。在这种情况下,您应该接受这样的事实:当出现问题时,业务数据和技术元数据可能会不同步。
这就是为什么提供自定义事务管理器的预期方法是通过自定义BatchConfigurer#getTransactionManager
,在这种情况下,您的自定义事务管理器会在这两个地方进行设置。这没有明确记录,但自 v4.1 以来已修复。这是提到的部分:配置作业存储库 https://docs.spring.io/spring-batch/docs/4.1.x/reference/html/job.html#javaConfig。 Javadoc中也提到了这一点@EnableBatchProcessing https://docs.spring.io/spring-batch/docs/4.3.x/api/org/springframework/batch/core/configuration/annotation/EnableBatchProcessing.html:
In order to use a custom transaction manager, a custom BatchConfigurer should be provided.
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)