Spring Batch Tasklet - Hello World Example | JavaInUse



Spring Batch Tasklet - Hello World example



A Step is a domain object that encapsulates an independent, sequential phase of a batch job and contains all of the information necessary to define and control the actual batch processing.

Steps can be processed in either of the following two ways.
  • Chunk
  • Tasklet
The Tasklet which is a simple interface with just one method execute. Using this we can perform single tasks like executing queries, deleting files. In a previous post we had seen the differences between Chunk and Tasklet processing. In this post we execute a simple tasklet for deleting a file.

Spring Batch - Table Of Contents

Spring Batch Hello World example-Write data from csv to xml file Spring Boot Batch Simple example Spring Batch - Difference between Step, Chunk and Tasklet Spring Batch Tasklet - Hello World example Spring Boot + Batch + Task Scheduler Example


Lets Begin-

The maven project we will be creating is as follows-
The pom.xml with spring batch dependencies is as follows-
<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 http://maven.apache.org/maven-v4_0_0.xsd">
	<modelVersion>4.0.0</modelVersion>
	<groupId>com.javainuse</groupId>
	<artifactId>spring-batch-tasklet</artifactId>
	<packaging>jar</packaging>
	<version>1.0-SNAPSHOT</version>

	<properties>
		<spring.version>3.2.2.RELEASE</spring.version>
		<spring.batch.version>2.2.0.RELEASE</spring.batch.version>
	</properties>


	<dependencies>
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-core</artifactId>
			<version></version>
		</dependency>


		<!-- Spring Batch dependencies -->
		<dependency>
			<groupId>org.springframework.batch</groupId>
			<artifactId>spring-batch-core</artifactId>
			<version></version>
		</dependency>

		<dependency>
			<groupId>org.springframework.batch</groupId>
			<artifactId>spring-batch-infrastructure</artifactId>
			<version></version>
		</dependency>

	</dependencies>


</project>
We create a class that implements the Tasklet interface and write logic to delete all the files from a folder.
package com.javainuse.tasklet;

import java.io.File;
import org.springframework.batch.core.StepContribution;
import org.springframework.batch.core.UnexpectedJobExecutionException;
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.InitializingBean;
import org.springframework.core.io.Resource;
import org.springframework.util.Assert;


public class FileDeletingTasklet implements Tasklet, InitializingBean {

	private Resource directory;

	@Override
	public void afterPropertiesSet() throws Exception {
		Assert.notNull(directory, "directory must be set");
	}

	@Override
	public RepeatStatus execute(StepContribution contribution,
			ChunkContext chunkContext) throws Exception {

		File dir = directory.getFile();
		Assert.state(dir.isDirectory());

		File[] files = dir.listFiles();
		for (int i = 0; i < files.length; i++) {
			boolean deleted = files[i].delete();
			if (!deleted) {
				throw new UnexpectedJobExecutionException(
						"Could not delete file " + files[i].getPath());
			} else {
				System.out.println(files[i].getPath() + " got deleted");
			}
		}
		return RepeatStatus.FINISHED;
	}

	public Resource getDirectory() {
		return directory;
	}

	public void setDirectory(Resource directory) {
		this.directory = directory;
	}
}

Next define the batch configuration batch-task.xml for creating the tasklet as follows-
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
	xmlns:batch="http://www.springframework.org/schema/batch" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://www.springframework.org/schema/batch 
		http://www.springframework.org/schema/batch/spring-batch-2.2.xsd
		http://www.springframework.org/schema/beans 
		http://www.springframework.org/schema/beans/spring-beans-3.2.xsd
		">

	<!-- Batch Config -->
	<bean id="jobRepository"
		class="org.springframework.batch.core.repository.support.MapJobRepositoryFactoryBean">
		<property name="transactionManager" ref="transactionManager" />
	</bean>

	<bean id="transactionManager"
		class="org.springframework.batch.support.transaction.ResourcelessTransactionManager" />

	<bean id="jobLauncher"
		class="org.springframework.batch.core.launch.support.SimpleJobLauncher">
		<property name="jobRepository" ref="jobRepository" />
	</bean>

	<bean id="fileDeletingTasklet" class="com.javainuse.tasklet.FileDeletingTasklet">
		<property name="directory" value="file:testdelete/deletefolder/" />
	</bean>

	<!-- Define Tasklet -->
	<job id="deleteTask" xmlns="http://www.springframework.org/schema/batch">
		<step id="deleteDir">
			<tasklet ref="fileDeletingTasklet" />
		</step>
	</job>

</beans>
Finally we load the Batch configuration and execute the tasklet.
package com.javainuse;

import org.springframework.batch.core.Job;
import org.springframework.batch.core.JobExecution;
import org.springframework.batch.core.JobParameters;
import org.springframework.batch.core.launch.JobLauncher;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class MainApp {

	public static void main(String[] args) {
		MainApp obj = new MainApp();
		obj.runBatchTask();
	}

	private void runBatchTask() {

		//load the batch config file
		String[] batchConfig = { "batch-task.xml" };
		ApplicationContext context = new ClassPathXmlApplicationContext(
				batchConfig);

		JobLauncher jobLauncher = (JobLauncher) context.getBean("jobLauncher");

		//load the job bean
		Job job = (Job) context.getBean("deleteTask");

		try {

			JobExecution execution = jobLauncher.run(job, new JobParameters());
			System.out.println("Job Exit Status : " + execution.getStatus());
		} catch (Exception e) {
			e.printStackTrace();
		}

		System.out.println("Completed");
	}
}

On Running any file existing in the deletefolder gets deleted.

Download Source Code

Download it -
Spring Batch Tasklet Hello World Example

See Also