Search Tutorials


Spring Boot Batch Tasklet Hello World | JavaInUse

Spring Boot Batch Tasklet Hello World

In previous tutorial we looked at Spring Batch Architecture. We also looked at the difference between Spring Batch Tasklet and Spring Batch Chunk processing. In this tutorial we will be implementing a hello world example to implement a spring batch tasklet. In the next tutorial we will be implementing Spring Boot Batch + Chunk Processing Hello World Example. As we have seen previously tasklets are used in scenarios where a simple task is to be performed. For example suppose we want to delete a file at a particular location. In such a scenario we will not use chunk based processing as itemreader and itemwriter will need to be blank and only in the itemprocessor we would be writing the delete logic. Following will be the spring boot project we will be implementing -
Spring Boot Batch Spring

Video

This tutorial is explained in the below Youtube Video.

Implementation

Go to Spring Initilizr to create the spring boot project.
Spring Boot Batch Spring Initializr
The maven project will be creating is as follows -
Spring Boot Batch Tasklet Hello World
The pom.xml will be as follows-
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
	<modelVersion>4.0.0</modelVersion>
	<parent>
		<groupId>org.springframework.boot</groupId>
		<artifactId>spring-boot-starter-parent</artifactId>
		<version>2.6.1</version>
		<relativePath /> <!-- lookup parent from repository -->
	</parent>
	<groupId>com.example</groupId>
	<artifactId>boot-batch-task-hello</artifactId>
	<version>0.0.1-SNAPSHOT</version>
	<name>boot-batch-task-hello</name>
	<description>Demo project for Spring Boot</description>
	<properties>
		<java.version>1.8</java.version>
	</properties>
	<dependencies>
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-batch</artifactId>
		</dependency>
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-web</artifactId>
		</dependency>

		<dependency>
			<groupId>com.h2database</groupId>
			<artifactId>h2</artifactId>
			<scope>runtime</scope>
		</dependency>
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-test</artifactId>
			<scope>test</scope>
		</dependency>
		<dependency>
			<groupId>org.springframework.batch</groupId>
			<artifactId>spring-batch-test</artifactId>
			<scope>test</scope>
		</dependency>
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-devtools</artifactId>
			<optional>true</optional>
		</dependency>
	</dependencies>

	<build>
		<plugins>
			<plugin>
				<groupId>org.springframework.boot</groupId>
				<artifactId>spring-boot-maven-plugin</artifactId>
			</plugin>
		</plugins>
	</build>

</project>
Modify the BootBatchTaskHelloApplication which is the bootstrap class by adding the EnableBatchProcessing annotation. This enables Spring Batch features and provide a base configuration for setting up batch jobs in @Configuration class.
package com.example.bootbatchtaskhello;

import org.springframework.batch.core.configuration.annotation.EnableBatchProcessing;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@EnableBatchProcessing
@SpringBootApplication
public class BootBatchTaskHelloApplication {

	public static void main(String[] args) {
		SpringApplication.run(BootBatchTaskHelloApplication.class, args);
	}

}




Next we will be creating the spring batch configuration class. In this class we autowire the JobBuilderFactory and StepBuilderFactory using which we create the spring batch job and spring batch step.
package com.example.bootbatchtaskhello;

import java.io.File;

import org.springframework.batch.core.Job;
import org.springframework.batch.core.Step;
import org.springframework.batch.core.StepContribution;
import org.springframework.batch.core.configuration.annotation.JobBuilderFactory;
import org.springframework.batch.core.configuration.annotation.StepBuilderFactory;
import org.springframework.batch.core.scope.context.ChunkContext;
import org.springframework.batch.core.step.tasklet.Tasklet;
import org.springframework.batch.repeat.RepeatStatus;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
public class BatchConfig {

	@Autowired
	private JobBuilderFactory jobFactory;

	@Autowired
	private StepBuilderFactory stepFactory;

	@Bean
	public Step step1() {
		return stepFactory.get("step1").tasklet(helloWorldTasklet()).build();
	}

	private Tasklet helloWorldTasklet() {
		return (new Tasklet() {
			@Override
			public RepeatStatus execute(StepContribution arg0, ChunkContext arg1) throws Exception {
				System.out.println("Deleting File");
				try {
					File f = new File("C:\\batch\\task1\\data.txt");
					if (f.delete()) {
						System.out.println(f.getName() + " deleted");
					} else {
						System.out.println("failed");
					}
				} catch (Exception e) {
					e.printStackTrace();
				}
				return RepeatStatus.FINISHED;
			}
		});

	}

	@Bean
	public Job helloWorldJob() {
		return jobFactory.get("helloworld").flow(step1()).end().build();
	}

}
Next we will be creating the controller class. In this class we expose a GET Rest API. When this GET call is made using the spring batch job launcher we trigger the spring batch job named helloWorldJob which we have defined in the configuration before.
package com.example.bootbatchtaskhello;

import org.springframework.batch.core.Job;
import org.springframework.batch.core.JobParameters;
import org.springframework.batch.core.JobParametersBuilder;
import org.springframework.batch.core.launch.JobLauncher;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class JobInvokerController {

	@Autowired
	JobLauncher jobLauncher;

	@Autowired
	Job helloWorldJob;

	@RequestMapping("/invokejob")
	public String handle() throws Exception {
		JobParameters jobParameters = new JobParametersBuilder().toJobParameters();
		jobLauncher.run(helloWorldJob, jobParameters);
		return "Task Batch job has been invoked";
	}

}

Finally in the application.properties file define the spring batch and h2 db configuration as follows -
spring.datasource.url=jdbc:h2:file:./DB
spring.jpa.properties.hibernate.hbm2ddl.auto=update
spring.batch.job.enabled=false
spring.batch.initialize-schema=always
spring.datasource.url=jdbc:h2:mem:testdb
Start the spring boot application. If we now go to localhost:8080/invokejob, the spring batch job will be started.
Spring Boot Batch Invoke Job
The spring batch delete tasklet gets executed. If we now go to the url - localhost:8080/h2-console/login.do. In the JDBC url use jdbc:h2:mem:testdb. Keep the password blank.Click on Connect. We can see the tables created by spring batch
Spring Boot Batch H2 database

Download Source Code

Download it - Spring Boot Batch Tasklet Hello World example