Java Reference
In-Depth Information
Each of the three methods of the ItemStream interface are called by Spring Batch during the
execution of a step. open is called to initialize any required state within your ItemReader. This includes
the opening of any files or database connections as well as when restarting a job. The open method could
be used to reload the number of records that had been processed so they could be skipped during the
second execution. update is used by Spring Batch as processing occurs to update that state. Keeping
track of how many records or chunks have been processed is a use for the update method. Finally, the
close method is used to close any required resources (close files, etc).
You will notice that the open and update provide access to the ExecutionContext that you did not
have a handle on in your ItemReader implementation. This is because Spring Batch will use the open
method to reset the state of the reader when a job is restarted. It will also use the update method to learn
the current state of the reader (which record you are currently on) as each item is processed. Finally, the
close method is used to clean up any resources used in the ItemStream.
Now you may be wondering how you can use the ItemStream interface for your ItemReader if it
doesn't have the read method. Short answer: you don't. Instead you'll use a utility interface,
org.springframework.batch.item.ItemStreamReader , that extends both the ItemStream and the
ItemReader interfaces. This will allow you to implement the ItemReader functionality as well as
maintain the state of your reader via Spring Batch. Listing 7-58 shows your CustomerItemReader
updated to implement the ItemStreamReader interface.
Listing 7-58. CustomerItemReader Implementing the ItemStreamReader Interface
package com.apress.springbatch.chapter7;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import org.springframework.batch.item.ExecutionContext;
import org.springframework.batch.item.ItemStreamException;
import org.springframework.batch.item.ItemStreamReader;
public class CustomerItemReader implements ItemStreamReader<Customer> {
private List<Customer> customers;
private int curIndex;
private String INDEX_KEY = "current.index.customers";
private String [] firstNames = {"Michael", "Warren", "Ann", "Terrence",
"Erica", "Laura", "Steve", "Larry"};
private String middleInitial = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
private String [] lastNames = {"Gates", "Darrow", "Donnelly", "Jobs",
"Buffett", "Ellison", "Obama"};
private String [] streets = {"4th Street", "Wall Street", "Fifth Avenue",
"Mt. Lee Drive", "Jeopardy Lane",
"Infinite Loop Drive", "Farnam Street",
"Isabella Ave", "S. Greenwood Ave"};
private String [] cities = {"Chicago", "New York", "Hollywood", "Aurora",
"Omaha", "Atherton"};
private String [] states = {"IL", "NY", "CA", "NE"};
 
Search WWH ::




Custom Search