Spring Batch 5 Job的JUnit5测试出现JobRepository Bean冲突问题
Spring Batch 5.0 JobRepository 重复定义错误解决方法
问题原因
你遇到的BeanDefinitionStoreException是因为重复注册了jobRepository bean:
SpringBatchTestConfig上的@EnableBatchProcessing注解会自动创建一套Spring Batch核心bean(包括jobRepository);HelloWorldJobConfig继承的DefaultBatchConfiguration是Spring Batch 5推荐的配置方式,同样会注册这些核心bean;
两者同时存在时,Spring容器无法确定使用哪个,就会抛出bean定义冲突的错误。
解决步骤
1. 移除测试配置类中的@EnableBatchProcessing
修改SpringBatchTestConfig,去掉@EnableBatchProcessing注解:
@Configuration @EnableAutoConfiguration public class SpringBatchTestConfig { }
2. 简化测试类的配置加载
@SpringBatchTest注解已经自动配置了测试所需的JobLauncherTestUtils和JobRepositoryTestUtils,测试类可以直接只加载业务配置类,无需额外指定测试配置:
@ExtendWith(SpringExtension.class) @SpringBatchTest @SpringBootTest(classes = HelloWorldJobConfig.class) public class HelloWorldJobConfigTest { @Autowired private JobLauncherTestUtils jobLauncherTestUtils; @Autowired private JobRepositoryTestUtils jobRepositoryTestUtils; @Test void success() throws Exception { // when JobExecution jobExecution = this.jobLauncherTestUtils.launchJob(); // then assertEquals(jobExecution.getExitStatus(), ExitStatus.COMPLETED); } }
3. 关于Spring Batch 5配置的说明
Spring Batch 5官方推荐使用DefaultBatchConfiguration(通过继承的方式)来配置Batch组件,替代旧版的@EnableBatchProcessing。如果需要自定义JobRepository、JobLauncher等核心组件,直接在继承DefaultBatchConfiguration的配置类中重写对应的方法即可,比如:
@Configuration public class HelloWorldJobConfig extends DefaultBatchConfiguration { // 自定义JobRepository @Override protected JobRepository createJobRepository() throws Exception { JobRepositoryFactoryBean factory = new JobRepositoryFactoryBean(); factory.setDataSource(dataSource()); factory.setTransactionManager(transactionManager()); factory.setIsolationLevelForCreate("ISOLATION_REPEATABLE_READ"); factory.setTablePrefix("BATCH_"); factory.setMaxVarCharLength(1000); return factory.getObject(); } // 其他Job、Step配置不变... }
内容的提问来源于stack exchange,提问作者SBS
相关产品推荐
相关产品推荐

