Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Spring Batch : custom ItemReader

I have a Spring Batch project with a simple custom reader and writer. When i run the code i end up with an endeless loop printing the first item "item 1". What am i doing wrong?

Here is my code:

Reader.java

public class Reader implements ItemReader<SimpleItem> {


public SimpleItem read() throws Exception, UnexpectedInputException, ParseException {
    if (getIterator().hasNext()) {
        return getIterator().next();
    }
    return null;
}

public Iterator<SimpleItem> getIterator() {
    List<SimpleItem> list = new ArrayList();
    list.add(new SimpleItem("item 1"));
    list.add(new SimpleItem("item 2"));
    return list.iterator();
}

}

Writer.java

public class Writer implements ItemWriter<SimpleItem> {
@Override
public void write(List<? extends SimpleItem> list) throws Exception {
    for(SimpleItem item : list) {
        System.out.println(item.getName()); // this prints item 1 endelessly
    }
}
}
like image 422
Armand Ndizigiye Avatar asked Jun 29 '26 08:06

Armand Ndizigiye


1 Answers

Every call to ItemReader#read begins with a call to Reader#getIterator which means you get a new list with every time you call to read. You really only want to create the list once.

We already have a List based ItemReader implementation. You can take a look at the code for it on Github here: https://github.com/spring-projects/spring-batch/blob/master/spring-batch-infrastructure/src/main/java/org/springframework/batch/item/support/ListItemReader.java

like image 167
Michael Minella Avatar answered Jun 30 '26 23:06

Michael Minella