简体   繁体   中英

Spring Batch Item Writer Listener not Working

I use spring batch and implemented item writer listener. My Item Writer Listener class is something like this

@Component
public class SomeItemWriterListener implements ItemWriteListener {

@Override
public void beforeWrite(List<Object> items) throws Exception {
    System.out.println("get here1");

}

@Override
public void afterWrite(List<Object> items) throws Exception {
    System.out.println("get here2");

}

@Override
public void onWriteError(List<Object> items, Exception ex) throws Exception {
    System.out.println("get here3");
}
}

Then I configure it in my step like this using Java Config

@Autowired
private SomeItemWriterListener writerListener;

@Bean
public Step step(StepBuilderFactory stepBuilderFactory,
    @Qualifier("itemReader")
        ItemReader<SomeItem> reader) {
    return stepBuilderFactory.get("step").listener(
        writerListener).chunk(
        chunkSize).reader(reader).processor(processor).writer(writer).build();
}

But, beforeWrite, afterWrite is not called. When I add some error onWriterError also not called. Did I miss something when I configure this?

Your are calling the StepBuilderHelper.listener(Object) method which, as you can see only is for annotation based listeners. Next to that you are trying to register the listener at the step level, whereas you should be registering it at the chunk level.

@Bean
public Step step(StepBuilderFactory stepBuilderFactory, @Qualifier("itemReader") ItemReader<SomeItem> reader) {
    return stepBuilderFactory.get("step")
            .chunk(chunkSize)
              .reader(reader)
              .processor(processor)
              .writer(writer)
              .listener(writerListener)
            .build();
}

This will call the appropriate listener(ItemWriteListener) method (there is also listener(Object) it might be needed that you need to cast to the ItemWriteListener interface to have the correct method invoked.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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