我有一个Spring Batch应用程序,在这里我必须重写像jobLauncher这样的bean。但是,当我尝试运行命令clean install时,出现了bean覆盖问题。它在我的本地计算机上运行良好,但是我在Jenkins上遇到了问题,我不知道为什么它在我的本地计算机上没有发生。
我查看了Spring代码,它们正在扩展配置类并覆盖Bean。我尝试扩展SimpleBatchConfiguration类,但是遇到了一些问题,我认为这不是一个好主意。
JobLaunher Bean in Application:
@Bean
public JobLauncher jobLauncher(JobRepository jobRepository) throws Exception {
SimpleJobLauncher jobLauncher = new SimpleJobLauncher();
jobLauncher.setTaskExecutor(new SimpleAsyncTaskExecutor());
jobLauncher.setJobRepository(jobRepository);
jobLauncher.afterPropertiesSet();
return jobLauncher;
}
JobLauncher in Spring Batch:
@Override
@Bean
public JobLauncher jobLauncher() throws Exception {
return createLazyProxy(jobLauncher, JobLauncher.class);
}
Error Logs:
APPLICATION FAILED TO START
***************************
Description:
The bean 'jobLauncher', defined in com.orange.alc.dabek.dataload.config.BatchConfiguration, could not be registered. A bean with that name has already been defined in class path resource [org/springframework/batch/core/configuration/annotation/SimpleBatchConfiguration.class] and overriding is disabled.
Action:
Consider renaming one of the beans or enabling overriding by setting spring.main.allow-bean-definition-overriding=true
2019-05-20 20:26:45.056 ERROR 12892 --- [ main] o.s.test.context.TestContextManager : Caught exception while allowing TestExecutionListener [org.springframework.test.context.web.ServletTestExecutionListener@29f8134] to prepare test instance [com.orange.alc.dabek.dataload.job.PhoneJobTest@611a2d82]
java.lang.IllegalStateException: Failed to load ApplicationContext
at org.springframework.test.context.cache.DefaultCacheAwareContextLoaderDelegate.loadContext(DefaultCacheAwareContextLoaderDelegate.java:125)
at org.springframework.test.context.support.DefaultTestContext.getApplicationContext(DefaultTestContext.java:108)
at org.springframework.test.context.web.ServletTestExecutionListener.setUpRequestContextIfNecessary(ServletTestExecutionListener.java:190)
at org.springframework.test.context.web.ServletTestExecutionListener.prepareTestInstance(ServletTestExecutionListener.java:132)
at org.springframework.test.context.TestContextManager.prepareTestInstance(TestContextManager.java:246)
at
我想覆盖spring批处理bean。我发现使用spring.main.allow-bean-definition-overriding = true不是一个好方法,因为它还隐藏了一些好处。我在application.yml中也找不到相同的属性。请让我知道更好的解决方案。
答案 0 :(得分:1)
为了自定义Spring Batch基础结构Bean(作业存储库,作业启动器,事务管理器等),您需要提供自定义BatchConfigurer
(请参阅参考文档的JavaConfig部分)。
您可以使您的批处理配置类从Spring Boot扩展org.springframework.boot.autoconfigure.batch.BasicBatchConfigurer
或从Spring Batch扩展org.springframework.batch.core.configuration.annotation.DefaultBatchConfigurer
并覆盖createJobLauncher
方法。