first_time_user
first_time_user

Reputation: 427

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?

Upvotes: 4

Views: 11676

Answers (1)

M. Deinum
M. Deinum

Reputation: 124526

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.

Upvotes: 6

Related Questions