问题
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
- Define a Bean with JobScope
- Use it in Step as usual
- 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