Spring Boot + Spring Batch + Java 8 : custom ItemReader

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)

compile("org.springframework.boot:spring-boot-starter-parent:1.4.1.RELEASE")
compile("org.apache.commons:commons-lang3:3.4");
compile("commons-io:commons-io:2.5");
compile("org.springframework.boot:spring-boot-starter-batch")

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.

art6

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

art1

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 :

art4

Batch step: import flags : reader

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

art9

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

art11

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:

art7

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:

art5

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).

art2

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

art3

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

Screenshot from my console:

art8

Let me know if you got any issues!

I’ll try to upload the full example on Github later.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s