Create a sample project

We can create a new spring project from site: start.spring.io with the following dependencies:

Lets create a sample tasklet flow with loggers so that we understand if the flow is working or not. Later we’ll add logic to fetch data from DB and insert in a excel file.

Lets add a Tasklet implementation first:
Now lets define steps and job and create beans for them:

Just one more steps before we test this setup. We need to initialize the schema for batch. For thats lets specify in the properties.

Thats it.

Lets test the flow.

Perfect. Its working as expected. The steps are getting created, our Tasklet is executed by the job.

Populate DB data to excel file

Further lets add code to read Employee data from DB and populate in an excel file. For that we’ll create Employee entity, Employee Repository and Excel Util class which will have the code to create and populate a excel file. For excel file operation’s we’ll need some dependencies to be added:

Dependency and Constants required in EmployeeUtil class:

Lets fetch the employees from DB and add call the writeToExcelFile() and pass filePath and employeeLists as paramters.

Lets test:

Ohh our step is not executing again as it has already been executed:

Lets solve this by telling spring batch to run our tasklet even if it has been executed before by calling the method allowStartIfComplete(true) before step build. Also instead of creating a new instance of tasklet everytime and passing into step. Lets mark it as component and Autowire it.

Now everything works fine. The records are getting fetched form DB and populated in the excel file:

Leave a Reply

Your email address will not be published. Required fields are marked *