DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Please enter at least three characters to search
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Zones

Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks

Last call! Secure your stack and shape the future! Help dev teams across the globe navigate their software supply chain security challenges.

Modernize your data layer. Learn how to design cloud-native database architectures to meet the evolving demands of AI and GenAI workloads.

Releasing software shouldn't be stressful or risky. Learn how to leverage progressive delivery techniques to ensure safer deployments.

Avoid machine learning mistakes and boost model performance! Discover key ML patterns, anti-patterns, data strategies, and more.

Related

  • How To Propagate Context Information Throw Spring Batch
  • High-Performance Batch Processing Using Apache Spark and Spring Batch
  • Batch Processing Large Data Sets with Spring Boot and Spring Batch
  • Migrating COBOL Batch to Spring Batch

Trending

  • Unlocking the Potential of Apache Iceberg: A Comprehensive Analysis
  • 5 Subtle Indicators Your Development Environment Is Under Siege
  • A Developer's Guide to Mastering Agentic AI: From Theory to Practice
  • How to Convert XLS to XLSX in Java
  1. DZone
  2. Culture and Methodologies
  3. Career Development
  4. Spring Batch - Hello World

Spring Batch - Hello World

By 
Tareq Abedrabbo user avatar
Tareq Abedrabbo
·
May. 23, 08 · News
Likes (0)
Comment
Save
Tweet
Share
299.0K Views

Join the DZone community and get the full member experience.

Join For Free

This is an introductory tutorial to Spring Batch. It does not aim to provide a complete guide to the framework but rather to facilitate the first contact. Spring Batch is quite rich in functionalities, and this is basically how I started learning it. Keep in mind that we will only be scratching the surface.

Before we start

All the examples will have the lofty task of printing "Hello World!" though in different ways. They were developed with Spring Batch 1.0. I'll provide a Maven 2 project and I'll run the examples with Maven but of course it is not a requirement to work with Spring Batch.

Spring Batch in 2 Words

Fortunately, Spring Batch model objects have self-explanatory names. Let's try to enumerate the most important and to link them together:

A batch Job is composed of one or more Steps. A JobInstance represents a given Job, parametrized with a set of typed properties called JobParameters. Each run of of a JobInstance is a JobExecution. Imagine a job reading entries from a data base and generating an xml representation of it and then doing some clean-up. We have a Job composed of 2 steps: reading/writing and clean-up. If we parametrize this job by the date of the generated data then our Friday the 13th job is a JobInstance. Each time we run this instance (if a failure occurs for instance) is a JobExecution. This model gives a great flexibility regarding how jobs are launched and run. This naturally brings us to launching jobs with their job parameters, which is the responsibility of JobLauncher. Finally, various objects in the framework require a JobRepository to store runtime information related to the batch execution. In fact, Spring Batch domain model is much more elaborate but this will suffice for our purpose.

Well, it took more than 2 words and I feel compelled to make a joke about it, but I won't. So let's move to the next section.

Common Objects

For each job, we will use a separate xml context definition file. However there is a number of common objects that we will need recurrently. I will group them in an applicationContext.xml which will be imported from within job definitions. Let's go through these common objects:

JobLauncher

JobLaunchers are responsible for starting a Job with a given job parameters. The provided implementation, SimpleJobLauncher, relies on a TaskExecutor to launch the jobs. If no specific TaskExecutor is set then a SyncTaskExecutor is used.

JobRepository

We will use the SimpleJobRepository implementation which requires a set of execution Daos to store its information.

JobInstanceDao, JobExecutionDao, StepExecutionDao

These data access objects are used by SimpleJobRepository to store execution related information. Two sets of implementations are provided by Spring Batch: Map based (in-memory) and Jdbc based. In a real application the Jdbc variants are more suitable but we will use the simpler in-memory alternative in this example.

Here's our applicationContext.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/beanshttp://www.springframework.org/schema/beans/spring-beans-2.5.xsd">

  <bean id="jobLauncher" class="org.springframework.batch.core.launch.support.SimpleJobLauncher">
      <property name="jobRepository" ref="jobRepository"/>
  </bean>
    
  <bean id="jobRepository" class="org.springframework.batch.core.repository.support.SimpleJobRepository">
      <constructor-arg>
          <bean class="org.springframework.batch.core.repository.dao.MapJobInstanceDao"/>
      </constructor-arg>
      <constructor-arg>
          <bean class="org.springframework.batch.core.repository.dao.MapJobExecutionDao" />
      </constructor-arg>
      <constructor-arg>
          <bean class="org.springframework.batch.core.repository.dao.MapStepExecutionDao"/>
      </constructor-arg>
  </bean>

</beans>

Hello World with Tasklets

A tasklet is an object containing any custom logic to be executed as a part of a job. Tasklets are built by implementing the Tasklet interface. Let's implement a simple tasklet that simply prints a message:

public class PrintTasklet implements Tasklet{

  private String message;

  public void setMessage(String message) {
      this.message = message;
  }
    
  public ExitStatus execute() throws Exception {
      System.out.print(message);
      return ExitStatus.FINISHED;
  }
}

Notice that the execute method returns an ExitStatus to indicate the status of the execution of the tasklet.

We will define our first job now in a simpleJob.xml application context. We will use the SimpleJob implementation which executes all of its steps sequentailly. In order to plug a tasklet into a job, we need a TaskletStep. I also added an abstract bean definition for tasklet steps in order to simplify the configuration:

<beans xmlns="http://www.springframework.org/schema/beans"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://www.springframework.org/schema/beanshttp://www.springframework.org/schema/beans/spring-beans-2.5.xsd">
                                
  <import resource="applicationContext.xml"/>
    
  <bean id="hello" class="helloworld.PrintTasklet">
      <property name="message" value="Hello"/>
  </bean>
    
  <bean id="space" class="helloworld.PrintTasklet">
      <property name="message" value=" "/>
  </bean>
   
  <bean id="world" class="helloworld.PrintTasklet">
      <property name="message" value="World!"/>
  </bean>

  <bean id="taskletStep" abstract="true"
      class="org.springframework.batch.core.step.tasklet.TaskletStep">
      <property name="jobRepository" ref="jobRepository"/>
  </bean>
    
  <bean id="simpleJob" class="org.springframework.batch.core.job.SimpleJob">
      <property name="name" value="simpleJob" />
      <property name="steps">
          <list>
              <bean parent="taskletStep">
                  <property name="tasklet" ref="hello"/>
              </bean>
              <bean parent="taskletStep">
                  <property name="tasklet" ref="space"/>
              </bean>
              <bean parent="taskletStep">;
                  <property name="tasklet" ref="world"/>
              </bean>
          </list>
      </property>
      <property name="jobRepository" ref="jobRepository"/>
  </bean>
</beans>

Running the Job

Now we need something to kick-start the execution of our jobs. Spring Batch provides a convenient class to achieve that from the command line: CommandLineJobRunner. In its simplest form this class takes 2 arguments: the xml application context containing the job to launch and the bean id of that job. It naturally requires a JobLauncher to be configured in the application context. Here's how to launch the job with Maven. Of course, it can be run with the java command directly (you need to specify the class path then):


mvn exec:java -Dexec.mainClass=org.springframework.batch.core.launch.support.CommandLineJobRunner 
-Dexec.args="simpleJob.xml simpleJob"

Hopefully, your efforts will be rewarded with a "Hello World!" printed on the console.

The code source can be downloaded here.

What's Next?

This is the first part of 3. In the next part we will improve on this example while the third part will be dedicated to item oriented steps and flat files readers and writers. Hope you find it useful.

Spring Batch Spring Framework career

Published at DZone with permission of Tareq Abedrabbo. See the original article here.

Opinions expressed by DZone contributors are their own.

Related

  • How To Propagate Context Information Throw Spring Batch
  • High-Performance Batch Processing Using Apache Spark and Spring Batch
  • Batch Processing Large Data Sets with Spring Boot and Spring Batch
  • Migrating COBOL Batch to Spring Batch

Partner Resources

×

Comments
Oops! Something Went Wrong

The likes didn't load as expected. Please refresh the page and try again.

ABOUT US

  • About DZone
  • Support and feedback
  • Community research
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Core Program
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 100
  • Nashville, TN 37211
  • support@dzone.com

Let's be friends:

Likes
There are no likes...yet! 👀
Be the first to like this post!
It looks like you're not logged in.
Sign in to see who liked this post!