gpt4 book ai didi

Spring Batch如何使用ItemReadListener

转载 作者:行者123 更新时间:2023-12-01 14:48:40 28 4
gpt4 key购买 nike

我使用 spring batch 来处理一个文件。所有组件的配置都是以编程方式进行的。

我有一个包含多个 TaskletSteps 的作业:

@Bean
@Named(SEEC_JOB)
public Job seecJob() {
return jobBuilderFactory.get(SEEC_JOB).start(seecMoveToWorkingStep()).next(seecLoadFileStep())
.on(ExitStatus.COMPLETED.getExitCode()).to(seecFlowMoveToArchiveOk()).from(seecLoadFileStep())
.on(ExitStatus.FAILED.getExitCode()).to(seecFlowMoveToArchiveKo()).end().build();

}

我的问题集中在 seecLoadFileStep() 上,详情如下:

@Bean
public TaskletStep seecLoadFileStep() {
TaskletStep build = stepBuilderFactory.get(SEEC_LOAD_FILE_STEP)
.<SeecMove, SeecMove>chunk(cormoranProperties.seec.batchSize.get()).reader(seecItemReader())
.writer(seecItemWriter()).build();
return build;
}

如果发生读取错误,我想抛出一个特定的异常(我的意思是读取错误:例如文件已损坏或错误,缺少 xml 标记...)。

我一直在阅读 spring batch 文档,我认为 ItemReadListener 是我的人选:

public interface ItemReadListener<T> extends StepListener {

void beforeRead();

void afterRead(T item);

void onReadError(Exception ex);

}

但是,我不知道怎么用!我已尝试通过我的 seecItemReader() 实现此接口(interface),但从未调用过 onReadError 方法。

我不知道如何在 taskletStep 中声明/注册 ItemReadListener。

这里是一些 spring 文档:

Any class that implements one of the extensions of StepListener (but not that interface itself since it is empty) can be applied to a step via the listeners element. The listeners element is valid inside a step, tasklet or chunk declaration. It is recommended that you declare the listeners at the level which its function applies, or if it is multi-featured (e.g. StepExecutionListener and ItemReadListener) then declare it at the most granular level that it applies (chunk in the example given).

An ItemReader, ItemWriter or ItemProcessor that itself implements one of the StepListener interfaces will be registered automatically with the Step if using the namespace element, or one of the the *StepFactoryBean factories. This only applies to components directly injected into the Step: if the listener is nested inside another component, it needs to be explicitly registered (as described above).

你能帮帮我吗?

提前致谢!

最佳答案

正如我猜测的那样,这比我想象的要容易,以编程方式注册 ItemReadListener 是通过 tasklet 配置中的监听器方法:

   @Bean
public TaskletStep seecLoadFileStep() {
TaskletStep build = stepBuilderFactory.get(SEEC_LOAD_FILE_STEP)
.<SeecMove, SeecMove>chunk(cormoranProperties.seec.batchSize.get()).reader(seecItemReader()).listener(seecItemReaderListener())
.writer(seecItemWriter()).build();
return build;
}

现在当异常发生时会调用 onError 方法。

关于Spring Batch如何使用ItemReadListener,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22637224/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com