How to use Spring Batch Tasklet

Spring Batch provides the Tasklet interface, to process a single task, such as clean or init resources before or after any step running. In the tutorial, JavaSampleApproach will guide you how to use Spring Batch Tasklet.

Related Posts:
How to start with Spring Batch using Spring Boot – Java Config
Spring Batch XML Config by Spring Boot
Spring Batch Job with Parallel Steps
Spring Batch – Programmatic Flow Decision
How to import CSV data to PostgreSQL Database using Spring Batch Job
Spring XD Option Module – Batch Job with PostgreSQL Datasource
How to use Spring Batch Restartable Function

I. Technologies

– Java 1.8
– Maven 3.3.9
– Spring Boot: 1.4.3.RELEASE
– Spring Tool Suite – Version 3.8.1.RELEASE

II. Overview
1. Project Structure

In the tutorial, we create a Job with 2 step:step1 -> step 2.
step1 processes a file C:\\readfile\\1.txt.
step2 is used to delete the file after processing by step1. So step2 is implemented by Tasklet.

Spring Batch tasklet project structure

2. Step to do

– Create Spring Boot project
– Implement Reader & Writer for step1

– Implement Tasklet for step2

– Config a Batch Job
– Implement JobLauncherController
– Run & Enjoy Results

III. Practice
1. Create Spring Boot project

– Open Spring Tool Suite, on main menu, choose File->New->Spring Starter Project, input project info. Press Next then Finish, a Spring Boot project will be created successfully.
Add needed dependencies:
spring-boot-starter-web
spring-boot-starter-batch
postgresql
Details:



	4.0.0

	com.javasampleapproach.springbatch
	SpringBatchTasklet
	0.0.1
	jar

	SpringBatchTasklet
	SpringBatchTasklet

	
		org.springframework.boot
		spring-boot-starter-parent
		1.5.1.RELEASE
		 
	

	
		UTF-8
		UTF-8
		1.8
	

	
		
			org.springframework.boot
			spring-boot-starter
		
		
		
			org.springframework.boot
			spring-boot-starter-web
		
		
		
		    org.springframework.boot
		    spring-boot-starter-batch
		
		
		
		
		    postgresql
		    postgresql
		    9.1-901-1.jdbc4
		

		
			org.springframework.boot
			spring-boot-starter-test
			test
		
	

	
		
			
				org.springframework.boot
				spring-boot-maven-plugin
			
		
	




2. Implement Reader & Write for step1

– Implement Reader:

package com.javasampleapproach.springbatch.step;
 
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.batch.item.ItemReader;
import org.springframework.batch.item.NonTransientResourceException;
import org.springframework.batch.item.ParseException;
import org.springframework.batch.item.UnexpectedInputException;
 
 
public class Reader implements ItemReader{
 
    private String[] files = {"C:\\readfile\\1.txt"};
     
    public int  count=0;
     
    Logger logger = LoggerFactory.getLogger(this.getClass());
     
    @Override
    public String read() throws Exception, UnexpectedInputException, ParseException, NonTransientResourceException {
         
        if(count < files.length){
            return files[count++];
        }else{
            count=0;
        }
        return null;
    }
}	

- Implement Writer:

package com.javasampleapproach.springbatch.step;
 
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.List;
import java.util.stream.Stream;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.batch.item.ItemWriter;
 
public class Writer implements ItemWriter {
 
    Logger logger = LoggerFactory.getLogger(this.getClass());
     
    @Override
    public void write(List paths) throws Exception {
        for(String filePath : paths){
        	System.out.println("filePath = " + filePath);
            try (Stream stream = Files.lines(Paths.get(filePath))) {
                stream.forEach(System.out::println);
            } catch (IOException e) {
            	throw(e);
            }
        }
    }
}
3. Implement Tasklet for step2

Create TaskletStep by implement: Tasklet interface. TaskletStep just deletes a file: C:\\readfile\\1.txt after step1's processing

package com.javasampleapproach.springbatch.tasklet;

import java.io.File;

import org.springframework.batch.core.StepContribution;
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.stereotype.Component;

@Component
public class TaskletStep implements Tasklet{

	@Override
	public RepeatStatus execute(StepContribution contribution, ChunkContext chunkContext) throws Exception {
		try{
    		File file = new File("C:\\readfile\\1.txt");
    		if(file.delete()){
    			System.out.println("### TaskletStep:" + file.getName() + " is deleted!");
    		}else{
    			System.out.println("Delete operation is failed.");
    		}
    	}catch(Exception e){
    		e.printStackTrace();
    	}
		return null;
	}
}
4. Config a Batch Job

Configure a Job with 2 step: step1->step2.

package com.javasampleapproach.springbatch.config;
 
import org.springframework.batch.core.Job;
import org.springframework.batch.core.Step;
import org.springframework.batch.core.configuration.annotation.JobBuilderFactory;
import org.springframework.batch.core.configuration.annotation.StepBuilderFactory;
import org.springframework.batch.core.launch.support.RunIdIncrementer;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import com.javasampleapproach.springbatch.step.Reader;
import com.javasampleapproach.springbatch.step.Writer;
import com.javasampleapproach.springbatch.tasklet.TaskletStep;
 
@Configuration
public class BatchConfig {
 
	@Autowired
	TaskletStep taskletStep;
	
    @Autowired
    public JobBuilderFactory jobBuilderFactory;
 
    @Autowired
    public StepBuilderFactory stepBuilderFactory;
 
     
    @Bean
    public Job job() {
        return jobBuilderFactory.get("job")
                .incrementer(new RunIdIncrementer())
                .start(step1()).next(step2())
                .build();
    }
 
    @Bean
    public Step step1() {
        return stepBuilderFactory.get("step1")
                . chunk(1)
                .reader(new Reader())
                .writer(new Writer())
                .build();
    }
    
    @Bean
    public Step step2() {
        return stepBuilderFactory.get("step2")
        		.tasklet(taskletStep)
                .build();
    }
}
5. Implement JobLauncherController

Implement JobLauncherController

package com.javasampleapproach.springbatch.controller;
 
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
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 JobLauncherController {
 
    @Autowired
    JobLauncher jobLauncher;
 
    @Autowired
    Job job;
 
    @RequestMapping("/launchjob")
    public String handle() throws Exception {
 
        Logger logger = LoggerFactory.getLogger(this.getClass());
        try {
        	JobParameters jobParameters = new JobParametersBuilder().addLong("time", System.currentTimeMillis())
                    .toJobParameters();
            jobLauncher.run(job, jobParameters);
        } catch (Exception e) {
            logger.info(e.getMessage());
        }
 
        return "Done!";
    }
}
6. Run & Enjoy Results

Build & Run the project with Spring Boot App mode.
Launch the Job by a request:
http://localhost:8080/launchjob
Logs:

Job: [SimpleJob: [name=job]] launched with the following parameters: [{time=1486471748444}]
o.s.batch.core.job.SimpleStepHandler     : Executing step: [step1]
filePath = C:\readfile\1.txt
line1
line2
line3
line4
line5
o.s.batch.core.job.SimpleStepHandler     : Executing step: [step2]
### TaskletStep:1.txt is deleted!
o.s.b.c.l.support.SimpleJobLauncher      : Job: [SimpleJob: [name=job]] completed with the following parameters: [{time=1486471748444}] and the following status: [COMPLETED]
IV. Sourcecode

SpringBatchTasklet

Leave a Reply

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