简体   繁体   English

Spring-Batch:如何在Spring Batch中的异常记录上返回自定义退出代码

[英]Spring-Batch : How do I return custom exit code on invalid record with exception in spring batch

我有一个春季批处理任务,在输入文件中我有很少的记录,一些记录是有效的,而一些记录是无效的。在有效记录上,它应该写入输出文件,对于无效的记录,它应该写入错误文件,但有一些例外问题是当将某些东西写入错误文件时,它应该将退出代码设置为3.我尝试了很多方法,但无法设置退出代码,甚至在发生异常时终止该记录的实例。所以它不叫作家。

You probably don't want to use an exception here. 您可能不想在这里使用异常。 As a general rule of thumb, it's best to avoid using exceptions for expected business logic. 根据一般经验,最好避免对预期的业务逻辑使用异常。 Instead, consider simply using your ItemProcessor to return a GoodObject (or the original item) if the record is valid and a BadObject if the record is invalid. 相反,如果记录有效,则考虑简单地使用ItemProcessor返回GoodObject (或原始项目),如果记录无效,则BadObject

Then, leverage a ClassifierCompositeItemWriter to send the good records to one file ItemWriter and the bad ones to the error file ItemWriter . 然后,利用ClassifierCompositeItemWriter将好记录发送到一个文件ItemWriter ,将坏记录发送到错误文件ItemWriter

Finally, there are a number of ways of determining whether or not any "bad" records are encountered. 最后,有多种方法可以确定是否遇到任何“不良”记录。 One simple way would be to put a class-level boolean in your ItemProcessor and then leverage the StepExecutionListener afterStep hook to check the flag and set the ExitCode . 一种简单的方法是在您的ItemProcessor放入一个类级别的boolean ,然后利用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;
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM