Spring batch: get ExecutionContext in the listener

流过昼夜 提交于 2021-02-05 09:44:25

问题


I am new to Spring batch. I need to count the element read, written and that have gone in error.

I've defined a step like this:

/*...*/

@Bean
public Step stepMain(StepBuilderFactory stepBuilderFactory) {
    return stepBuilderFactory.get("stepMain").<T, T> chunk(this.chuckSize).reader(reader(null, null)).processor(new Processor()).writer(writer()).faultTolerant().skipPolicy(new AlwaysSkipItemSkipPolicy()).listener(new ListenerReader()).listener(new ListenerProcessor()).listener(new ListenerWriter()).listener(new ListenerChunk()).build();
}

/*...*/

And, for example, an ListenerReader like this:

@Log4j2
public class ListenerReader implements ItemReadListener<T> {

    @Value("#{jobExecution.executionContext}")
    private ExecutionContext executionContext;

    @Override
    public void afterRead(T item) {
        Integer read = (Integer) executionContext.get("reportRead");
        read++;
        executionContext.put("reportRead", read);
    }

    @Override
    public void onReadError(Exception ex) {
        Integer error = (Integer) executionContext.get("reportError");
        error++;
        executionContext.put("reportError", error);
    }

}

But in ListenerReader i've no visibility of executionContext field. How can i solve?


回答1:


You can do it like

  1. Define a Bean with JobScope
  2. Use it in Step as usual
  3. Inject it via Listener.

Below is an example

@Bean
@JobScope
public SimpleReaderListener simpleReaderListener() {
      return new SimpleReaderListener();
}

@Bean
public Step step1() {
    return stepBuilderFactory.get("step1").<SoccerTeam, SoccerTeam> chunk(1)
            .reader(simpleReader()).listener(simpleReaderListener()).processor(new SimpleProcessor())
            .writer(new SimpleWriter()).build();
}

public class SimpleReaderListener implements ItemReadListener<SoccerTeam> {

    @Value("#{jobExecution.executionContext}")
    private ExecutionContext executionContext;

    @Override
    public void afterRead(SoccerTeam soccerTeam) {

    }


来源:https://stackoverflow.com/questions/63936622/spring-batch-get-executioncontext-in-the-listener

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!