首页 > 解决方案 > 未调用步骤之前的弹簧批处理,需要步骤执行上下文

问题描述

在我的春季批处理工作流配置中,我有如下项目编写器:

@Bean
@Scope(value = "step", proxyMode = ScopedProxyMode.INTERFACES)
public ItemWriter<Price> skippedItemWriter(@Value("#{stepExecution.executionContext}") ExecutionContext executionContext) {
    return new SkippedItemWriter(executionContext);
}


public class SkippedItemWriter implements ItemWriter<Price>, StepExecutionListener {

    private static final Logger LOGGER = getLogger(SkippedItemWriter.class);

    private final ExecutionContext executionContext;
    private StepExecution stepExecution;

    public SkippedItemWriter(final ExecutionContext executionContext) {
        this.executionContext = executionContext;
    }

    @Override
    public void write(List<? extends Price> items) {

        if (CollectionUtils.isEmpty(items)) {
            return;
        }
        /blah 
    }

    @Override
    public void beforeStep(StepExecution stepExecution) {
        LOGGER.info("in beforeStep");
        this.stepExecution = stepExecution;
    }

    @Override
    public ExitStatus afterStep(StepExecution stepExecution) {
        return null;
    }
}

我的前一步和后一步没有被调用。

bean 必须是步骤范围的。

我正在尝试获取我在前面步骤中设置的发布计数:

ExecutionContext context = stepContribution.getStepExecution().getJobExecution().getExecutionContext();
context.putInt((PUBLISH_COUNT.name()), 0);

我尝试返回SkippedItemWriter()而不是返回,ItemWriter<T>但出现另一个代理错误。

我应该添加 SkippedItemWriter 是复合编写器的一部分:

@Bean
@Scope(value = "step", proxyMode = ScopedProxyMode.INTERFACES)
public ItemWriter<Price> compositeWriter() {
    CompositeItemWriter<Price> itemWriter = new CompositeItemWriter<>();
itemWriter.setDelegates(Arrays.asList(
              skippedItemWriter(null)));

        return itemWriter;   }

标签: javaspringspring-batch

解决方案


原因是由于您SkippedItemWriter是复合项目编写器的代表,它不会自动注册为侦听器,这应该手动完成。这是文档的拦截步骤执行部分的摘录:

If the listener is nested inside another component, it needs to be explicitly
registered (as described previously under "Registering ItemStream with a Step").

因此,您需要SkippedItemWriter在您的步骤中明确地将 注册为侦听器。


推荐阅读