在创建 spring 批处理 bean 时获取“当前线程的作用域‘步骤’未激活”

DBr*_*ker 6 spring spring-batch

在我的 Spring 批处理配置中,我试图设置一个分区步骤,它从 JobParameters 访问值,如下所示:

@Bean
@Qualifier("partitionJob")
public Job partitionJob() throws Exception {

    return jobBuilderFactory
            .get("partitionJob")
            .incrementer(new RunIdIncrementer())
            .start(partitionStep(null))
            .build();
}

@Bean
@StepScope //I'm getting exception here - > Error creating bean 
public Step partitionStep(
        @Value("#{jobParameters[gridSize]}") String gridSize)
        throws Exception {

    return stepBuilderFactory
            .get("partitionStep")
            .partitioner("slaveStep", partitioner())
            .gridSize(
                    StringUtils.isEmpty(gridSize) ? 10 : Integer
                            .parseInt(gridSize))
            .step(slaveStep(50000))
            .taskExecutor(threadPoolTaskExecutor()).build();
}

@Bean
@StepScope
public Step slaveStep(int chunkSize) throws Exception {

    return stepBuilderFactory
            .get("slaveStep")
            .<Person,Person> chunk(chunkSize)
            .reader(jdbcPagingItemReader()),
            .writer(csvFileWriterParts())
            .listener(stepExecutionListener()).build();
}
Run Code Online (Sandbox Code Playgroud)

我在 SpringBoot 应用程序中添加了 @EnableBatchProcessing 注释。

由于我想在构建步骤时访问 JobParameters,所以我使用了 @StepScope。我有一个工作正常的示例,没有 @StepScope 注释,但在这种情况下,我没有访问任何 JobParameters 或上下文中的任何内容。

但是如果我在 partitionStep 上使用 StepScope 注释,我会得到

创建名为“scopedTarget.partitionStep”的 bean 时出错:当前线程的作用域“step”未激活;如果您打算从单例中引用它,请考虑为此 bean 定义一个范围代理;嵌套异常是 java.lang.IllegalStateException:没有可用于步骤范围的上下文持有者

但是如果我将它更改为 JobScope,那么它会在 slaveStep() 失败并显示相同的错误消息。

在这种情况下使用的正确范围是什么以及如何解决我遇到的这个问题?

在配置 spring bean 时访问 JobParameters 的更好方法是什么?

异常堆栈如下

2018-05-25 21:07:32,075 错误 [main] org.springframework.batch.core.job.AbstractJob:执行作业 org.springframework.beans.factory.BeanCreationException 时遇到致命错误:创建名为“scopedTarget.partitionStep”的 bean 时出错': 当前线程的作用域 'step' 未激活;如果您打算从单例中引用它,请考虑为此 bean 定义一个范围代理;嵌套异常是 java.lang.IllegalStateException: No context holder available for step scope at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:361) at org.springframework.beans.factory.support.AbstractBeanFactory。 getBean(AbstractBeanFactory.java:197) at org.springframework.aop.target.SimpleBeanTargetSource.getTarget(SimpleBeanTargetSource.java:35) at org.

如果我修改为JobScope,我会在slaveStep上得到异常,这类似于上面的异常。

DBr*_*ker 3

请尝试使用 Manh 发布的选项Spring batch range issues while using spring boot 。我想它解决了问题。不幸的是,我无法再访问代码库,以确认我为修复所做的工作。