:::: MENU ::::

Spring Batch

Creation of the project with Spring Boot

We go to https://start.spring.io/ and we generate a Spring Boot project with Batch and HSQLDB (that is a embedded database to persist the metadata Batch operations). We download it and import as Maven project in our Eclipse.

Job, Step and Tasklet

Now we create a new component with two properties that Spring will auto-instantiate: one of type JobBuilderFactory and the other of type StepBuilderFactory.

We create a Step using the previous factory and a Tasklet (an interface that is used to do something simple), that will print a text string on the console.

After that, we create a Job, that will execute the previous Step.

MyJobConfig.java

package com.luisgomezcaballero.springbatchdemo;

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.EnableBatchProcessing;
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
@EnableBatchProcessing
public class MyJobConfig {

	@Autowired
	private JobBuilderFactory jobBuilderFactory;
	
	@Autowired
	private StepBuilderFactory stepBuilderFactory;
	
	@Bean
	public Step myStep() {
		return stepBuilderFactory.get("myStep").tasklet(new Tasklet() {
			
			@Override
			public RepeatStatus execute(StepContribution arg0, ChunkContext arg1) throws Exception {
				System.out.println("myTasklet");
				return RepeatStatus.FINISHED;
			}
		}).build();
	}
	
	@Bean
	public Job myJob() {
		return jobBuilderFactory.get("myJob").start(myStep()).build();
	}
	
}

Demonstration

Right click on SpringBatchApplication, Run As, Java Application. The specified Jobs will be executed and we will see our message on the console.

Repository

The code of this demo project is located at https://github.com/luisgomezcaballero/spring-batch-demo.


So, what do you think ?