javasetup

Spring Batch : Hello World!


This java tutorial will guide you to build a basic spring batch application. It covers Workspace setup, Project creation, Coding and Running the project ,every detail
so that you get almost a hands-on experiance on setting up your first spring batch application.



In this section we will not use any build tools like Maven/Gradle instead we will manually add all the dependency jars into classpath
and let our IDE do the project building.



1. Prerequisites

Before we start coding let us first tell you the tools we used and the libraries we need for spring batch development.

Tools Used
  Eclipse    [Any version 4.2(Juno) or above . We are using 4.7(oxygen).]

JDK version
  JDK 1.6     [We are using JDK 1.6 to build this application.]

Jars Required
  We need following dependency jars to build the application. [Download link provided within]


Download all jars


	
Now we are done with all the things we need to build a basic spring batch application. Lets get started then. Open eclipse and follow below steps .

2. Create a Java project


Of course you know how to do it, but we will not skip any step .

Follow the steps , read inline instructions.

Step 1
Spring Batch
Goto File --> New --> Java Project

Step 2
Spring Batch
Give a name to your application and click on Finish button.

	
Now we have created a Java Projet in eclipse. Next step is to add the downloaded jars into the build path of this project.

3. Configure Build Path


Steps to configure build path in eclipse. Read inline instructions.

Step 1
Spring Batch
Right-Click on the project
Goto Build Path
Click on Configure Build Path

Step 2
Spring Batch
Click on Add Exsternal Jars... button

Step 3
Spring Batch
Navigate to the directory where the jars has been downloaded.
Select all the downloaded jars and click on Open.

Step 4
Spring Batch
Click on apply and close button.

	
Now we are done with configuring build path. Lets start coding :)

4. Code


This application contains following files :

1. jobConfiguration.xml - Batch job configuration xml
2. DemoTasklet.java - Batch job Tasklet class
3. context.xml - Spring Application context(Defining JobLauncher)
4. JobController.java - Batch job invoker class

  • Review Directory structure of the project in below screen. Read inline comments.
Project structure in eclipse
Spring Batch
Package config contains configuration xmls
Package com.javasetup.springbatch.tasklets contains DemoTasklet class
Package com.javasetup.springbatch.contoller contains JobController class



  • At a minimum, launching a batch job requires two things: the Job to be launched and a JobLauncher.
A Job is an entity that encapsulates an entire batch process. As is common with other Spring projects, a Job will be wired together via an XML configuration file or Java based configuration. This configuration may be referred to as the job configuration.

Lets configuring a job first as shown in jobConfiguration.xml.
  • Include Spring Batch namespace.
  • Define a job which contains a step demoStep.
  • Define a tasklet inside demoStep.
  • The tasklet class DemoTasklet defined in bean tag which contains the processing code of the Spring Batch application.
  • Use import tag to locate context.xml file.
jobConfiguration.xml

<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 "> 
   <import resource="context.xml" />      
   <!-- Defining a bean --> 
   <bean id="tasklet" class="com.javasetup.springbatch.tasklets.DemoTasklet" />  
   <!-- Defining a job--> 
   <batch:job id="demoJob">  
      <!-- Defining a Step --> 
      <batch:step id="demoStep"> 
         <tasklet ref="tasklet"/>   
      </batch:step>    
   </batch:job>  
</beans>  
	


  • The Tasklet is a simple interface that has one method, execute.
  • Method execute either returns RepeatStatus.FINISHED or throws an exception to signal a failure.
  • Each call to the Tasklet is wrapped in a transaction.
Write the processing code inside DemoTasklet.java. Here we are just printing Hello Spring Batch message.

DemoTasklet.java


package com.javasetup.springbatch.tasklets;

    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;

    public class DemoTasklet implements Tasklet {

	public RepeatStatus execute(StepContribution arg0, ChunkContext arg1) throws Exception {
		System.out.println("Hello Spring batch"); 
		return RepeatStatus.FINISHED; 
	}

} 
    
	


Next step is to create a JobLauncher that executes the created Job(demoJob).
  • A JobLauncher represents a simple interface for launching a Job with a given set of JobParameters.
  • The most basic implementation of the JobLauncher interface is the SimpleJobLauncher. Its only required dependency is a JobRepository, in order to obtain an execution.
  • Configure spring context to define demoJobLauncher(a JobLauncher), jobRepository and transactioManager bean as shown in the context.xml below.
context.xml

   <beans xmlns="http://www.springframework.org/schema/beans" 
   xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
   xsi:schemaLocation="http://www.springframework.org/schema/beans 
      http://www.springframework.org/schema/beans/spring-beans-3.2.xsd">  
   
   <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="demoJobLauncher" 
      class="org.springframework.batch.core.launch.support.SimpleJobLauncher"> 
      <property name="jobRepository" ref="jobRepository" /> 
   </bean> 
   </beans> 
	



5. Run the Job

  • Create the job launcher.
  • Create the job.
  • Execute the job using run method of jobLauncher.
JobController.java

package com.javasetup.springbatch.contoller;

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 JobController {

	public static void main(String[] args) throws Exception {
		  System.out.println("Inside Spring bactch Job controller [Start]"); 
	      String[] springConfig  =  {"config/jobConfiguration.xml"};  
	      
	      // Creating the application context object  
	      ApplicationContext context = new ClassPathXmlApplicationContext(springConfig); 
	      
	      // Creating the job launcher 
	      JobLauncher jobLauncher = (JobLauncher) context.getBean("demoJobLauncher"); 
	  
	      // Creating the job 
	      Job job = (Job) context.getBean("demoJob"); 
	  
	      // Executing the JOB 
	      JobExecution execution = jobLauncher.run(job, new JobParameters()); 
	      System.out.println("Excution Status : " + execution.getStatus());
	      System.out.println("Inside Spring bactch Job controller [End]");
	}

}
    
	


  • To execute the application , follow below step.
Execute Application
Spring Batch
Right-Click on the JobController.java
Select Run As -> Java Aplication


Console Output

Inside Spring bactch Job controller [Start]
23 Jul, 2018 12:46:16 AM org.springframework.context.support.ClassPathXmlApplicationContext prepareRefresh
INFO: Refreshing org.springframework.context.support.ClassPathXmlApplicationContext@1113708: startup date [Mon Jul 23 00:46:16 IST 2018]; root of context hierarchy
23 Jul, 2018 12:46:16 AM org.springframework.beans.factory.xml.XmlBeanDefinitionReader loadBeanDefinitions
INFO: Loading XML bean definitions from class path resource [config/jobConfiguration.xml]
23 Jul, 2018 12:46:17 AM org.springframework.beans.factory.xml.XmlBeanDefinitionReader loadBeanDefinitions
INFO: Loading XML bean definitions from class path resource [config/context.xml]
23 Jul, 2018 12:46:17 AM org.springframework.beans.factory.support.DefaultListableBeanFactory registerBeanDefinition
INFO: Overriding bean definition for bean 'demoJob': replacing [Generic bean: class [org.springframework.batch.core.configuration.xml.SimpleFlowFactoryBean]; scope=; abstract=false; lazyInit=false; autowireMode=0; dependencyCheck=0; autowireCandidate=true; primary=false; factoryBeanName=null; factoryMethodName=null; initMethodName=null; destroyMethodName=null] with [Generic bean: class [org.springframework.batch.core.configuration.xml.JobParserJobFactoryBean]; scope=; abstract=false; lazyInit=false; autowireMode=0; dependencyCheck=0; autowireCandidate=true; primary=false; factoryBeanName=null; factoryMethodName=null; initMethodName=null; destroyMethodName=null]
23 Jul, 2018 12:46:17 AM org.springframework.beans.factory.support.DefaultListableBeanFactory preInstantiateSingletons
INFO: Pre-instantiating singletons in org.springframework.beans.factory.support.DefaultListableBeanFactory@121ab80: defining beans [jobRepository,transactionManager,demoJobLauncher,tasklet,org.springframework.batch.core.scope.internalStepScope,org.springframework.beans.factory.config.CustomEditorConfigurer,org.springframework.batch.core.configuration.xml.CoreNamespacePostProcessor,demoStep,demoJob]; root of factory hierarchy
23 Jul, 2018 12:46:17 AM org.springframework.batch.core.launch.support.SimpleJobLauncher afterPropertiesSet
INFO: No TaskExecutor has been set, defaulting to synchronous executor.
23 Jul, 2018 12:46:18 AM org.springframework.batch.core.launch.support.SimpleJobLauncher run
INFO: Job: [FlowJob: [name=demoJob]] launched with the following parameters: [{}]
23 Jul, 2018 12:46:18 AM org.springframework.batch.core.job.SimpleStepHandler handleStep
INFO: Executing step: [demoStep]
Hello Spring batch
23 Jul, 2018 12:46:18 AM org.springframework.batch.core.launch.support.SimpleJobLauncher run
INFO: Job: [FlowJob: [name=demoJob]] completed with the following parameters: [{}] and the following status: [COMPLETED]
Excution Status : COMPLETED
Inside Spring bactch Job controller [End]
    
	

In this section we will use Maven to build the project.



1. Prerequisites

Before we start coding let us first tell you the tools we used and the libraries we need for spring batch development.

Tools Used
  Eclipse     [Any version 4.2(Juno) or above . We are using 4.7(oxygen).]
  Maven     [Plugin version 3.1 ]

JDK & Libraries
  JDK 1.8     [We are using JDK 1.8 to build this application.]
  Spring Core 4.3.18.RELEASE
  Spring Batch 3.0.7.RELEASE

    Thats all.
	now we can start developing the application.
	

2. Create a Maven project


Of course you know how to do it, but we will not skip any step .

Follow the steps , read inline instructions.

Step 1
Spring Batch
Goto File --> New --> Other


Step 2
Spring Batch
Maven --> Maven Project . Click on next button.


Step 3
Spring Batch
Check Create a simple project as shown.
Check Use default Workspace location as shown.
Click on next button.


Step 4
Spring Batch
Write Group Id .
Write Artifact Id(jar name) .
Write Name.
Click on Finish button.


    With that step 4 we are done with creating a Maven Projet in eclipse.
	


  • Review Directory structure of the project just after creating it in below screen.
Project structure in eclipse
Spring Batch


3. Configure Build Path

  • We will configure the build path using maven.
  • To do that we need to mention dependencies in pom.xml.
  • This application needs only these two dependencies
       1. Spring Core 4.3.18.RELEASE.
       2. Spring Batch 3.0.7.RELEASE.
  • Content of pom.xml shared below
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.javasetup.springbatch</groupId>
  <artifactId>SpringBatchMaven</artifactId>
  <version>0.0.1-SNAPSHOT</version>
  <name>SpringBatchMaven</name>  
  <properties>
		<spring.version>4.3.18.RELEASE</spring.version>
		<spring.batch.version>3.0.7.RELEASE</spring.batch.version>
  </properties>		
<dependencies>
<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-core</artifactId>
    <version>${spring.version}</version>
</dependency>
<dependency>
    <groupId>org.springframework.batch</groupId>
    <artifactId>spring-batch-core</artifactId>
    <version>${spring.batch.version}</version>
</dependency>
</dependencies>	
</project>
	


  • Follow below step to add dependencies into build path.
Step 1
Spring Batch
Right-Click on the project.
Go to Maven -> Update Project...

Step 2
Spring Batch
Click OK in the Update Maven Project pop-up.


  • Below jars will get downloaded and addded to the classpath automatically by Maven.
Maven Dependencies
Spring Batch
	
Now we are done with configuring build path. Lets start coding :)

4. Code


This application contains following files :

1. pom.xml - Maven config file
2. jobConfiguration.xml - Batch job configuration xml
3. DemoTasklet.java - Batch job Tasklet class
4. context.xml - Spring Application context(Defining JobLauncher)
5. JobController.java - Batch job invoker class

  • Review Directory structure of the project in below screen. Read inline comments.
Project structure in eclipse
Spring Batch
Inside resources directory Package config contains configuration xmls
Inside java directory Package com.javasetup.springbatch.tasklets contains DemoTasklet class
Inside java directory Package com.javasetup.springbatch.contoller contains JobController class


  • We hve already talked about pom.xml file. Find the pom.xml content below.
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.javasetup.springbatch</groupId>
  <artifactId>SpringBatchMaven</artifactId>
  <version>0.0.1-SNAPSHOT</version>
  <name>SpringBatchMaven</name>  
  <properties>
		<spring.version>4.3.18.RELEASE</spring.version>
		<spring.batch.version>3.0.7.RELEASE</spring.batch.version>
  </properties>		
<dependencies>
<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-core</artifactId>
    <version>${spring.version}</version>
</dependency>
<dependency>
    <groupId>org.springframework.batch</groupId>
    <artifactId>spring-batch-core</artifactId>
    <version>${spring.batch.version}</version>
</dependency>
</dependencies>	
</project>
	


  • At a minimum, launching a batch job requires two things: the Job to be launched and a JobLauncher.
A Job is an entity that encapsulates an entire batch process. As is common with other Spring projects, a Job will be wired together via an XML configuration file or Java based configuration. This configuration may be referred to as the job configuration.

Lets configuring a job first as shown in jobConfiguration.xml.
  • Include Spring Batch namespace.
  • Define a job which contains a step demoStep.
  • Define a tasklet inside demoStep.
  • The tasklet class DemoTasklet defined in bean tag which contains the processing code of the Spring Batch application.
  • Use import tag to locate context.xml file.
jobConfiguration.xml

<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 "> 
   <import resource="context.xml" />      
   <!-- Defining a bean --> 
   <bean id="tasklet" class="com.javasetup.springbatch.tasklets.DemoTasklet" />  
   <!-- Defining a job--> 
   <batch:job id="demoJob">  
      <!-- Defining a Step --> 
      <batch:step id="demoStep"> 
         <tasklet ref="tasklet"/>   
      </batch:step>    
   </batch:job>  
</beans>  
	


  • The Tasklet is a simple interface that has one method, execute.
  • Method execute either returns RepeatStatus.FINISHED or throws an exception to signal a failure.
  • Each call to the Tasklet is wrapped in a transaction.
Write the processing code inside DemoTasklet.java. Here we are just printing Hello Spring Batch message.

DemoTasklet.java


package com.javasetup.springbatch.tasklets;

    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;

    public class DemoTasklet implements Tasklet {

	public RepeatStatus execute(StepContribution arg0, ChunkContext arg1) throws Exception {
		System.out.println("Hello Spring batch"); 
		return RepeatStatus.FINISHED; 
	}

} 
    
	


Next step is to create a JobLauncher that executes the created Job(demoJob).
  • A JobLauncher represents a simple interface for launching a Job with a given set of JobParameters.
  • The most basic implementation of the JobLauncher interface is the SimpleJobLauncher. Its only required dependency is a JobRepository, in order to obtain an execution.
  • Configure spring context to define demoJobLauncher(a JobLauncher), jobRepository and transactioManager bean as shown in the context.xml below.
context.xml

   <beans xmlns="http://www.springframework.org/schema/beans" 
   xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
   xsi:schemaLocation="http://www.springframework.org/schema/beans 
      http://www.springframework.org/schema/beans/spring-beans-3.2.xsd">  
   
   <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="demoJobLauncher" 
      class="org.springframework.batch.core.launch.support.SimpleJobLauncher"> 
      <property name="jobRepository" ref="jobRepository" /> 
   </bean> 
   </beans> 
	



5. Run the Job

  • Create the job launcher.
  • Create the job.
  • Execute the job using run method of jobLauncher.
JobController.java

package com.javasetup.springbatch.contoller;

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 JobController {

	public static void main(String[] args) throws Exception {
		  System.out.println("Inside Spring bactch Job controller [Start]"); 
	      String[] springConfig  =  {"config/jobConfiguration.xml"};  
	      
	      // Creating the application context object  
	      ApplicationContext context = new ClassPathXmlApplicationContext(springConfig); 
	      
	      // Creating the job launcher 
	      JobLauncher jobLauncher = (JobLauncher) context.getBean("demoJobLauncher"); 
	  
	      // Creating the job 
	      Job job = (Job) context.getBean("demoJob"); 
	  
	      // Executing the JOB 
	      JobExecution execution = jobLauncher.run(job, new JobParameters()); 
	      System.out.println("Excution Status : " + execution.getStatus());
	      System.out.println("Inside Spring bactch Job controller [End]");
	}

}
    
	


  • To execute the application , follow below step.
Execute Application
Spring Batch
Right-Click on the JobController.java
Select Run As -> Java Aplication


Console Output

Inside Spring bactch Job controller [Start]
Aug 11, 2018 6:15:16 PM org.springframework.context.support.ClassPathXmlApplicationContext prepareRefresh
INFO: Refreshing org.springframework.context.support.ClassPathXmlApplicationContext@156ce6a: startup date [Sat Aug 11 18:15:16 IST 2018]; root of context hierarchy
Aug 11, 2018 6:15:17 PM org.springframework.beans.factory.xml.XmlBeanDefinitionReader loadBeanDefinitions
INFO: Loading XML bean definitions from class path resource [config/jobConfiguration.xml]
Aug 11, 2018 6:15:18 PM org.springframework.beans.factory.xml.XmlBeanDefinitionReader loadBeanDefinitions
INFO: Loading XML bean definitions from class path resource [config/context.xml]
Aug 11, 2018 6:15:20 PM org.springframework.batch.core.launch.support.SimpleJobLauncher afterPropertiesSet
INFO: No TaskExecutor has been set, defaulting to synchronous executor.
Aug 11, 2018 6:15:22 PM org.springframework.batch.core.launch.support.SimpleJobLauncher run
INFO: Job: [FlowJob: [name=demoJob]] launched with the following parameters: [{}]
Aug 11, 2018 6:15:22 PM org.springframework.batch.core.job.SimpleStepHandler handleStep
INFO: Executing step: [demoStep]
Hello Spring batch
Aug 11, 2018 6:15:22 PM org.springframework.batch.core.launch.support.SimpleJobLauncher run
INFO: Job: [FlowJob: [name=demoJob]] completed with the following parameters: [{}] and the following status: [COMPLETED]
Excution Status : COMPLETED
Inside Spring bactch Job controller [End]

    
	


References