cp5
cp5

Reputation: 1133

Is there a way to intercept and inject another object before calling the writer in spring batch?

I am making use of Spring Batch.

The flow reading items from a file is like below:

Picture from the official Spring batch documentation Flow of item reader

I am making use of a batch chunk.

<batch:step id="myImportStep">
    <batch:tasklet>
        <batch:chunk reader="myFileItemReader" processor="myFileProcessor" writer="myFileWriter" chunk-completion-policy="myCompletionPolicy" skip-limit="1000000" retry-limit="3">
            ... Some excetions and listeners
        </batch:chunk>
    </batch:tasklet>
</batch:step>

I have a file that I process in my item reader where I read line by line and then in my processor I create my own custom order object. After each 10th order item create, according the completion policy, the list of order objects gets passed to the writer to action the actual orders.

My business case says when executing the writer process (aka when I have a list of 10 order objects created) go and run some logic to see if an additional order object needs to be created.

public class myWriter implements ItemWriter<OrderObject> {

    public void write(final List<? extends OrderObject> items) throws Exception {

        //apply logic here to see if an additional order should be created
        //problem is that the list of items cannot be modified to add more items to it
        //which make sense... if the itemWriter gets called in chunks of 10 then you simply 
        //can't add a new order in between. What I am looking to do... is there way to access this 
        //list of orders to add more to it... or another suggestion on how to add the original list of
        //orders and to be able to add more

But I don't know how to obtain access to the original order list that is created by the processor. Even if I can add orders at the back of the list that will be send to the Writer again at a later stage. Any other suggestions on how to do such a thing?

Based on the question from Kayaman: I agree I could create a new ArrayList<>(items) and add or modify the list. But that will not alter the main list of items that gets passed from one step to another.

The interface for the ItemWriter takes in a List parameter:

package org.springframework.batch.item;

import java.util.List;

public interface ItemWriter<T> {
    void write(List<? extends T> var1) throws Exception;
}

Upvotes: 1

Views: 1316

Answers (1)

Karl Alexander
Karl Alexander

Reputation: 371

Why not use the beforeWrite() method of ItemWriteListener?

Called before ItemWriter.write(java.util.List)

See : https://docs.spring.io/spring-batch/trunk/apidocs/org/springframework/batch/core/ItemWriteListener.html

Upvotes: 2

Related Questions