春季批次中的覆盖 Bean 问题

Vim*_*wan 3 java spring spring-batch spring-boot

我有一个 spring 批处理应用程序,我必须在其中覆盖像 jobLauncher 这样的 bean。但是当我尝试运行命令 clean install 时,我遇到了 bean 覆盖问题。它在我的本地机器上运行良好,但我在 Jenkins 上遇到了问题,我不知道为什么它没有发生在我的本地机器上。

我查看了他们正在扩展配置类并覆盖 bean 的 spring 代码。我尝试扩展 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 
Run Code Online (Sandbox Code Playgroud)

我想覆盖春季批豆。我发现使用 spring.main.allow-bean-definition-overriding=true 不是一个好方法,因为它也隐藏了一些好处。我也没有在我的 application.yml 中找到相同的属性。请让我知道更好的解决方案。

Mah*_*ine 9

为了自定义 Spring Batch 基础设施 bean(作业存储库、作业启动器、事务管理器等),您需要提供自定义BatchConfigurer(请参阅参考文档的JavaConfig部分)。

您可以使您的批处理配置类org.springframework.boot.autoconfigure.batch.BasicBatchConfigurer从 Spring Boot 或org.springframework.batch.core.configuration.annotation.DefaultBatchConfigurerSpring Batch扩展并覆盖该createJobLauncher方法。