【问题标题】:Spring-Batch : How do I return custom exit code on invalid record with exception in spring batchSpring-Batch:如何在 Spring Batch 中返回无效记录上的自定义退出代码并出现异常
【发布时间】:2026-01-21 00:50:01
【问题描述】:

我有一个 spring 批处理任务,其中我的输入文件中的记录很少,有些是有效的,有些是无效的。在有效记录上,它应该写入输出文件,对于无效记录,它应该写入错误文件处理器抛出了一些异常。所以问题是当将某些内容写入错误文件时,它应该将退出代码设置为 3。我尝试了很多方法,但它无法设置退出代码。它甚至终止了该记录的实例发生异常时不会调用 writer。

【问题讨论】:

  • 欢迎来到 SO。您应该参观并阅读minimal reproducible example 部分,以最大限度地获得积极反馈和帮助您的问题的机会!

标签: java spring spring-mvc spring-batch spring-batch-admin


【解决方案1】:

您可能不想在这里使用异常。作为一般经验法则,最好避免对预期的业务逻辑使用异常。相反,如果记录有效,请考虑简单地使用您的ItemProcessor 返回GoodObject(或原始项目),如果记录无效,则返回BadObject

然后,利用ClassifierCompositeItemWriter 将好的记录发送到一个文件ItemWriter,将坏记录发送到错误文件ItemWriter

最后,有多种方法可以确定是否遇到任何“坏”记录。一种简单的方法是将类级别的boolean 放入您的ItemProcessor,然后利用StepExecutionListener afterStep 挂钩检查标志并设置ExitCode

public class ValidatingItemProcessor implements ItemProcessor<Input, AbstractItem>, StepExecutionListener {

    private boolean itemFailed = false;

    @Override
    public AbstractItem process(final Input item) throws Exception {
        if (item.isValid()) {
            return new GoodItem();
        }
        itemFailed = true;
        return new BadItem();
    }

    @Override
    public void beforeStep(final StepExecution stepExecution) {
        //no-op
    }

    @Override
    public ExitStatus afterStep(final StepExecution stepExecution) {
        if (itemFailed) {
            return new ExitStatus("3");
        }
        return null;
    }
}

【讨论】:

    最近更新 更多