With Spring Batch : I would like to publish all chunks items to another repository (some sort of messaging queue). But before publishing them, I need to make sure the transaction succeeds properly (my Writer is a JPA Repository).
I know there’s ItemWriteListener
interface and void afterWrite(Chunk items)
But this method is called before the end of transaction
I know there’s also ChunkListener
interface and void afterChunk(ChunkContext context)
method. This is good because afterChunk(ChunkContext context)
is called after the end of transaction.
Unfortunatly ChunkContext
object doesn’t give access to chunk items.
I was thinking of this solution mixing ItemWriteListener
and ChunkListener
Is this a good approach ?
I use here a temp List to store all items from a chunk
public class ItemListener implements ItemWriteListener<Object> {
public List<Object> list = new ArrayList<>();
public void afterWrite(Chunk<? extends Object> items) {
list.clear();
list.addAll(items.getItems());
}
public List<Object> getList() {
return List.copyOf(list);
}
}
And then I use the previous list containing items :
public class ChunkListenerImpl implements ChunkListener {
private ItemListener itemListener;
public ChunkListenerImpl(ItemListener itemListener) {
this.itemListener = itemListener;
}
public void afterChunk(ChunkContext context) {
itemListener.getList().forEach(item -> {
apiClient.publish(item);
});
}
}