What is Spring Batch – Environmental Setup, Features, Example

We offer you a brighter future with FREE online courses - Start Now!!

1. Spring Batch Tutorial

In this Spring Batch Tutorial, you will be learning about the Spring Batch and the features of it. Along with that, you will develop an enterprise application example so as to make you understand the use of Spring Batch in the practical world. Before proceeding through this article, you should know the basics of Java programming.

Spring Batch Tutorial - A Complete Tour 2018

Spring Batch Tutorial – A Complete Tour 2018

2. Why Do We Need for Batch in Spring Framework?

Before starting with a Spring Batch tutorial, you should know about batch processing. Batch processing is a mode which involves executing the series of automated jobs which are complex without user interaction. In simple words, a Batch process handles large volume data and runs it for a long time.

Let’s Explore More Features of Spring Framework

Many enterprise applications need to process high volume data to perform several functions such as:

  • Periodic time-based calculations.
  • Applications that are periodic and are processed repetitively over large datasets.
  • Applications which requires processing and validating the data available.

3. What is Spring Batch?

Spring Batch, is a lightweight framework used for developing batch applications that are used in an enterprise application. It provides a very effective framework for processing large volume batch jobs. Therefore, this topic is for those developers who are required to use a large volume of records which involves processing statistic, management of resources etc.

Other tasks of Spring Batch along with bulk processing are:

Here is the architecture of Spring Batch:

Spring Batch Architecture

Spring Batch Architecture

The components of Spring Batch architecture are described as follow:

  • Application: It contains all jobs and code for Spring Framework.
  • Batch core: It has all the API classes required for controlling and launching Batch.
  • Batch infrastructure: It has readers and writers along with services used by both above components.

4. Features of Batch in Spring

Some of the characteristic features of Spring Batch are:

Features of Spring Batch

Features of Spring Batch

a. Flexibility

The Spring Batch application is very flexible. You just need to change an XML file to alter the order of processing an application.

b. Scalability

The Spring Batch application can easily be scaled using the portioning techniques. These techniques allow you to execute each thread and steps of job in parallel.

Read About Spring IoC Containers – Types of Spring Container

c. Maintainability

A Spring batch job has steps with each step can be decoupled, tested without affecting other steps.

d. Reliability

The Spring Batch applications are very reliable as you can restart any job from the point where your application failed. It is done by decoupling the steps.

e. Multiple ways of launching the job

You have the power of using web applications or Java programs or even command line for launching Spring Batch job.

5. Setting up the Environment

Before you go for the example application for Spring Batch you need to know about the setting up of an environment. Following are the steps required for setting the environment of Spring Batch:

  • Install Eclipse on your machine and open a new project in it.
  • Create a sample Spring Batch project.
  • After this right click on the project, you have created and then convert that into a Maven project. As you convert it into Maven it will show you Pom.xml. There you have to mention the dependency. After that, the jar files will get automatically download in your project.

Do you know how to Install Spring Framework – Spring Framework Environment Setup

  • In the pom.xml copy paste the below content and refresh it:
<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>example</groupId>
         <artifactId>SpringBatchSample</artifactId>
         <packaging>jar</packaging>
         <version>1.0-SNAPSHOT</version>
         <name>SpringBatchExample</name>
         <url>http://maven.apache.org</url>
<properties>
         <jdk.version>1.8</jdk.version>
         <spring.version>4.3.8.RELEASE</spring.version>
         <spring.batch.version>3.0.7.RELEASE</spring.batch.version>
         <mysql.driver.version>5.1.25</mysql.driver.version>
         <junit.version>4.11</junit.version>
</properties>
<dependencies>
     <!-- Spring Core -->
     <dependency>
         <groupId>org.springframework</groupId>
         <artifactId>spring-core</artifactId>
         <version>${spring.version}</version>
</dependency>
<!-- Spring jdbc, for database -->
<dependency>
         <groupId>org.springframework</groupId>
         <artifactId>spring-jdbc</artifactId>
         <version>${spring.version}</version>
</dependency>
<!-- Spring XML to/back object -->
<dependency>
         <groupId>org.springframework</groupId>
         <artifactId>spring-oxm</artifactId>
         <version>${spring.version}</version>
</dependency>
<!-- MySQL database driver -->
<dependency>
         <groupId>mysql</groupId>
         <artifactId>mysql-connector-java</artifactId>
         <version>${mysql.driver.version}</version>
</dependency>
<!-- Spring Batch dependencies -->
<dependency>
         <groupId>org.springframework.batch</groupId>
         <artifactId>spring-batch-core</artifactId>
         <version>${spring.batch.version}</version>
</dependency>
<dependency>
         <groupId>org.springframework.batch</groupId>
         <artifactId>spring-batch-infrastructure</artifactId>
         <version>${spring.batch.version}</version>
</dependency>
<!-- Spring Batch unit test -->
<dependency>
         <groupId>org.springframework.batch</groupId>
         <artifactId>spring-batch-test</artifactId>
         <version>${spring.batch.version}</version>
</dependency>
<!-- Junit -->
<dependency>
         <groupId>junit</groupId>
         <artifactId>junit</artifactId>
         <version>${junit.version}</version>
         <scope>test</scope>
</dependency>
</dependencies>
<build>
     <finalName>spring-batch</finalName>
     <plugins>
       <plugin>
         <groupId>org.apache.maven.plugins</groupId>
         <artifactId>maven-eclipse-plugin</artifactId>
         <version>2.9</version>
         <configuration>
         <downloadSources>true</downloadSources>
         <downloadJavadocs>false</downloadJavadocs>
     </configuration>
</plugin>
<plugin>
         <groupId>org.apache.maven.plugins</groupId>
         <artifactId>maven-compiler-plugin</artifactId>
         <version>2.3.2</version>
        <configuration>
                  <source>${jdk.version}</source>
                  <target>${jdk.version}</target>
                </configuration>
             </plugin>
          </plugins>
       </build>
   </project>

6. Spring Batch Example

Now after getting to know about Spring batch, it is features and setting of environments you will see a working example. The Spring Batch contains the following files:

  • Configuration file: It is an XML file where job and steps of a job will get defined.
  • Context.xml: In this define beans like repository, launcher and transaction manager.
  • Tasklet class: For this write the code for processing job.
  • Launcher class: In this class, you will launch a Batch application by launching the Job launcher.

Let’s learn the Integration of MVC with Spring

a. jobConfig.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 = "a_sample.MyTasklet" />
      <!-- Defining a job-->
      <batch:job id = "helloWorldJob">
            <!-- Defining a Step -->
            <batch:step id = "step1">
               <tasklet ref = "tasklet"/>
            </batch:step>
      </batch:job>
</beans>

b. 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 = "jobLauncher"
       class = "org.springframework.batch.core.launch.support.SimpleJobLauncher">
       <property name = "jobRepository" ref = "jobRepository" />
     </bean>
</beans>

c. Tasklet.java

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 MyTasklet implements Tasklet {
      @Override
    public RepeatStatus execute(StepContribution arg0, ChunkContext arg1) throws Exception {
     System.out.println("Hello This is a sample example of spring batch");
     return RepeatStatus.FINISHED;
   }
}

d. App.java

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 App {
     public static void main(String[] args)throws Exception {
// System.out.println("hello");
          String[] springConfig = {"a_sample/job_hello_world.xml"};
// Creating the application context object
          ApplicationContext context = new                               ClassPathXmlApplicationContext(springConfig);
// Creating the job launcher
          JobLauncher jobLauncher = (JobLauncher) context.getBean("jobLauncher");
// Creating the job
          Job job = (Job) context.getBean("helloWorldJob");
// Executing the JOB
          JobExecution execution = jobLauncher.run(job, new JobParameters());
          System.out.println("Exit Status : " + execution.getStatus());
    }
}

Let’s Look at Spring Boot CLI – Features, Installation, Example

e. Output

The following output you will achieve:

Jun 20,2018 4:40:54 PM org.springframework.context.support.AbstractApplicationContext prepareRefresh
INFO:Refreshing org.springframework.context.support.ClassPathXmlApplicationContext@2ef1e4fa: startup date; root of context hierarchy

Jun 20,2018 4:40:54 PM org.springframework.beans.factory.xml.XmlBeanDefinitionReader loadBeanDefinitions INFO: Loading XML bean definitions

Jun 20,2018 4:40:54 PM org.springframework.beans.factory.xml.XmlBeanDefinitionReader loadBeanDefinitions
INFO: Loading XML bean definitions

Jun 20,2018 4:40:54 PM org.springframework.beans.factory.support.DefaultListableBeanFactory preInstantiateSingletons

Jun 20,2018 4:40:55 PM org.springframework.batch.core.launch.support.SimpleJobLauncher afterPropertiesSet
INFO: No TaskExecutor has been set, defaulting to a synchronous executor.

Jun 20,2018 4:40:55 PM org.springframework.batch.core.launch.support.SimpleJobLauncher$1 run
INFO: Job: [FlowJob: [name=helloWorldJob]] launched with the following parameters: [{}]

Jun 20,2018 4:40:55 PM org.springframework.batch.core.job.SimpleStepHandler handleStep INFO: Executing step: [step1]
Hello This is a sample example of spring batch

Jun 20,2018 4:40:55 PM org.springframework.batch.core.launch.support.SimpleJobLauncher$1 run
INFO: Job: [FlowJob: [name=helloWorldJob]] completed with the following parameters: [{}] and the following status: [COMPLETED]

Exit Status: COMPLETED

So, this was all about Spring Batch Tutorial. Hope you like our explanation.

7. Summary of Spring Batch Tutorial

Hence, in this session, you studied the Spring batch, which is used for developing a batch application. Along with this, we discussed the need for using batch processing. Also, you learned about the features of Spring batch and its architectural components and environment setup. The working example helped you get insights about the Spring Batch. Still, if you have any query, feel free to ask in the comment section.

Related Topic- Spring Custom Event

For reference

Did you like this article? If Yes, please give DataFlair 5 Stars on Google

follow dataflair on YouTube

Leave a Reply

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