Simple example of using a custom ItemReader for Spring Batch, with Spring boot and Java 8.

This example describe how to run a batch where the source data is a list of files.

Dependencies (using Gradle)


Source data: files

Let’s have a folder that contains the list of flags of the world. The file name is the ISO 3166-2 code of a country.

First we have to create a simple bean that have two fields and one constructor :

Batch step: import flags

A batch step is composed of three main items:

  • Reader : read data from source
  • Writer : write data to destination
  • Processor : transform an object from source into a new object

Those three objects should be instantiated in a new class :

Batch step: import flags: reader

First let’s declare our reader in the class PangeaBatchStepImportFlags:

The FileReader object is a new class to create that implements ItemReader:

Batch step: import flags: writer

Our writer class does nothing complicated, it just prints to the console each item details: the ISO 3166-2 country code and the file associated.

Add the following method to the class PangeaBatchStepImportFlags:

As ItemWriter is a functional interface, we can simply return a lambda expression.

Batch step: import flags: processor

In our example we don’t need to transform the source object into another one, so let’s use a processor that returns the same object that is passed.

Add the following method to the class PangeaBatchStepImportFlags:

Main Batch class

This class is the one that will run the batch step by step. For this you have to use the annotation EnableBatchProcessing, declare a job factory, a step factory and the class that represents your step to execute (one step = one class).

Then, you have to declare the order of execution of the steps.

Then just run your server and you’ll see that the batch job will be well executed!

Screenshot from my console:

Let me know if you got any issues!