Tuesday 24 November 2020

Spring Batch: Provide parameters to a job

In this post, I am going to explain how to pass parameters to a job.

 

This is two-step process.

a.   Pass parameters as command line arguments

b.   Read the parameters using @Value annotation.

 

Step 1: Pass parameters as command line arguments.

java {Application_Name} arg1=value1 arg2=value2….

 

Step 2: Read command line arguments using @Value annotation.

@Bean
@StepScope
public Tasklet tasklet1(@Value("#{jobParameters['sleepTime']}") Integer sleepTime) {
	return (StepContribution contribution, ChunkContext chunkContext) -> {

		System.out.println("Going to sleep for " + sleepTime + " seconds");
		TimeUnit.SECONDS.sleep(sleepTime);
		System.out.println("Tasklet resumed from sleep");

		return RepeatStatus.FINISHED;

	};
}

@Bean
public Step step1() {
	return this.stepBuilderFactory.get("step1").tasklet(tasklet1(null)).build();
}

 

"#{jobParameters['sleepTime']}"

Above snippet reads the value of command line argument ‘sleepTime’.

 

As you see, I created Tasklet using @StepScope annotaton. StepScope beans are lazily instantiated. By specifying a spring batch component being StepScope means that Spring Batch will use the spring container to instantiate a new instance of that component for each step execution. This is required to lately bind the job parameters.

 

Find the below working application.

 

Step 1: Create new maven project ‘job-parameters-demo’.

 

Step 2: Update pom.xml with maven dependencies.

 

pom.xml

 

<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/xsd/maven-4.0.0.xsd">
	<modelVersion>4.0.0</modelVersion>
	<groupId>com.sample.app</groupId>
	<artifactId>job-parameters-demo</artifactId>
	<version>1</version>

	<parent>
		<groupId>org.springframework.boot</groupId>
		<artifactId>spring-boot-starter-parent</artifactId>
		<version>2.1.6.RELEASE</version>
	</parent>

	<properties>
		<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
	</properties>

	<dependencies>

		<!-- https://mvnrepository.com/artifact/org.springframework.batch/spring-batch-core -->
		<dependency>
			<groupId>org.springframework.batch</groupId>
			<artifactId>spring-batch-core</artifactId>
		</dependency>

		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-web</artifactId>
		</dependency>

		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-data-jpa</artifactId>
		</dependency>

		<dependency>
			<groupId>com.h2database</groupId>
			<artifactId>h2</artifactId>
		</dependency>
	</dependencies>
</project>


Step 3: Create new package ‘com.sample.app.configuration’ and define JobConfiguration.

 

JobConfiguration.java

package com.sample.app.configuration;

import java.util.concurrent.TimeUnit;

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.configuration.annotation.StepScope;
import org.springframework.batch.core.repository.JobRepository;
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.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.transaction.PlatformTransactionManager;

@Configuration
@EnableBatchProcessing
public class JobConfiguration {
	@Autowired
	private JobBuilderFactory jobBuilderFactory;

	@Autowired
	private StepBuilderFactory stepBuilderFactory;

	@Bean
	@StepScope
	public Tasklet tasklet1(@Value("#{jobParameters['sleepTime']}") Integer sleepTime) {
		return (StepContribution contribution, ChunkContext chunkContext) -> {

			System.out.println("Going to sleep for " + sleepTime + " seconds");
			TimeUnit.SECONDS.sleep(sleepTime);
			System.out.println("Tasklet resumed from sleep");

			return RepeatStatus.FINISHED;

		};
	}

	@Bean
	public Step step1() {
		return this.stepBuilderFactory.get("step1").tasklet(tasklet1(null)).build();
	}

	@Bean
	public Job myJob(JobRepository jobRepository, PlatformTransactionManager platformTransactionManager) {

		return jobBuilderFactory.get("My-First-Job").start(step1()).build();
	}

}


Step 4: Define App.java.

 

App.java

package com.sample.app;

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

@EnableBatchProcessing
@SpringBootApplication
public class App {

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


Step 5: Create ‘application.properties’ file under src/main/resources folder.

 

application.properties

logging.level.root=ERROR
logging.level.org.hibernate=ERROR

## H2 specific properties
spring.h2.console.enabled=true
spring.h2.console.path=/h2

spring.datasource.url=jdbc:h2:file:~/db/myOrg.db;DB_CLOSE_ON_EXIT=FALSE;DB_CLOSE_DELAY=-1;

spring.datasource.username=krishna
spring.datasource.password=password123

spring.datasource.driverClassName=org.h2.Driver

## JPA specific properties
# Creates the schema, destroying previous data.
spring.jpa.hibernate.ddl-auto=create-drop

spring.jpa.database-platform=org.hibernate.dialect.H2Dialect

spring.jpa.show-sql=false
spring.jpa.properties.hibernate.format_sql=false

## Database connection pooling properties
# Number of ms to wait before throwing an exception if no connection is available.
spring.datasource.max-wait=10000

# Maximum number of active connections that can be allocated from this pool at the same time.
spring.datasource.tomcat.max-active=10
spring.datasource.tomcat.max-idle=5
spring.datasource.tomcat.min-idle=3


Total project structure looks like below.






How to run the application in Eclipse?

Right click on App.java -> Run As -> Run Configurations.





Under 'Arguments' section add below statement.

sleepTime=3





Click on Run button to run the application. You will see below messages in console.

 

Going to sleep for 3 seconds

Tasklet resumed from sleep

 

You can download complete working application from this link.

https://github.com/harikrishna553/springboot/tree/master/batch/job-parameters-demo

Previous                                                    Next                                                    Home

No comments:

Post a Comment