I have created my custom ItemReader:
@Component("pricereader")
public class MyItemReader implements ItemReader<Price>{
@Override
public Price read() throws Exception, UnexpectedInputException, ParseException,
NonTransientResourceException {
// TODO Auto-generated method stub
return null;
}
}
Calling it in a job thus defined:
<batch:job id="job1">
<batch:step id="step1">
<batch:tasklet>
<batch:chunk reader="pricereader" processor="priceprocessor" writer="pricewriter" commit-interval="1"/>
</batch:tasklet>
</batch:step>
</batch:job>
This itemReader has to parse data from an external file. I could think about something like this:
private Scanner scanner;
public MyItemReader(String filepath){
//initializing scanner
}
Anyway I found that constructor is called on spring initialization and I don't like the idea of keeping an open connection to a file in memory. Moreover I'd like to use this ItemReader to read data from multiple files so adding this information inside the constructor is not great as well...any ideas?
What you are describing is exactly what the ItemStream interface is for. The ItemStream interface. The ItemStream interface provides facilities for state management of a Spring Batch component. It includes an open, update, and close method intended specifically for the purpose of initializing state, persisting any state needed, and cleaning up any state. In your case, opening a file would be done in the open method and the close method would handle closing the handle. These methods are called automatically via the Spring Batch framework and are used for the same thing in readers like the FlatFileItemReader.
In fact, since the use of the ItemStream interface in conjunction with the ItemReader interface is so common, we have an aggregate interface ItemStreamReader that extends both. You can read more about the ItemStream interface in the documentation here: http://docs.spring.io/spring-batch/trunk/reference/html/readersAndWriters.html#itemStream
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With