05
Feb
10

Hello World With Spring Batch 2.0.x


A newer version of this page is available here: https://numberformat.wordpress.com/2013/12/27/hello-world-with-spring-batch-3-0-x-with-pure-annotations/

This page describes how to get a Spring Batch application to print hello world to the console. This page provides a stepping stone to help you get up and running quickly. Since this is a quick and dirty method of getting up and running with spring batch, it does not cover the fundamental concepts.  For further information please visit the Spring Batch project documentation site seen in the resource section at the bottom.

This page takes about 10 minutes to complete and have a working spring batch application.

Background

The following spring batch example program is the simplest way you could setup a job to run in Spring batch. As such there are some limitations with the following approach.

Use of an In Memory Database

The following program uses an uses in memory database to store information about batch execution runs. This means that there is no protection against duplicate job runs and it does not store when a job was started or completed. Since spring is a pluggable architecture you can always change to use a persistent database like mysql or oracle to store job information. I will describe this process in a future blog entry.

If you use scheduling tools like Autosys you should already have a system that maintains information about job executions. These tools would maintain the history of past runs and if the job succeeded or not etc…so using an in-memory database should not big deal.

Requirements

  • Java 5
  • Maven 2 – installed and configured

Create the project using Maven Archetype

First step is to create the job using a maven archetype. Open up the command prompt and navigate to an empty directory.

mvn archetype:generate -DarchetypeArtifactId=maven-archetype-quickstart
groupId: com.test
artifactId: springBatchHelloWorld

Answer the rest of the questions with defaults “Just hit the enter key”

Change to the project’s base directory.

cd springBatchHelloWorld

Create the resources folder

mkdir -p src/main/resources

Modify the pom.xml

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/maven-v4_0_0.xsd">
  <modelVersion>4.0.0</modelVersion>
  <groupId>com.test</groupId>
  <artifactId>springBatchHelloWorld</artifactId>
  <packaging>jar</packaging>
  <version>1.0-SNAPSHOT</version>
  <name>springBatchHelloWorld</name>
  <url>http://maven.apache.org</url>
  <dependencies>
    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>3.8.1</version>
      <scope>test</scope>
    </dependency>

        <dependency>
            <groupId>org.springframework.batch</groupId>
            <artifactId>spring-batch-core</artifactId>
            <version>2.0.4.RELEASE</version>
        </dependency>
 	<dependency>
		<groupId>commons-lang</groupId>
		<artifactId>commons-lang</artifactId>
		<version>2.1</version>
	</dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring</artifactId>
            <version>2.5.6</version>
        </dependency>

  </dependencies>
    <build>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <version>2.0.2</version>
                <configuration>
                    <source>1.5</source>
                    <target>1.5</target>
                </configuration>
            </plugin>
        </plugins>
    </build>
</project>

Spring Application Context

Spring Batch is a very robust batch execution environment. There are a few supporting objects that need to be in place even if we are not going to use their full capabilities.

In the following configuration file we will be setting up

  • jobRepository – this is the in-memory database
  • jobLauncher –
  • transactionManager – dummy transaction manager

src/main/resources/applicationContext.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans:beans xmlns="http://www.springframework.org/schema/batch"
	xmlns:beans="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-2.0.xsd

http://www.springframework.org/schema/batch

http://www.springframework.org/schema/batch/spring-batch-2.0.xsd">

<beans:bean id="jobRepository"
class="org.springframework.batch.core.repository.support.MapJobRepositoryFactoryBean">
<beans:property name="transactionManager" ref="transactionManager"/>
</beans:bean>

	<beans:bean id="jobLauncher"
		class="org.springframework.batch.core.launch.support.SimpleJobLauncher">
		<beans:property name="jobRepository" ref="jobRepository" />
	</beans:bean>

	<beans:bean id="transactionManager" class="org.springframework.batch.support.transaction.ResourcelessTransactionManager"/>
</beans:beans>

Job Definition File

The following file contain the specific details of the helloWorld job we want to run.

src/main/resources/simpleJob.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans:beans xmlns="http://www.springframework.org/schema/batch"
     xmlns:beans="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-2.0.xsd

http://www.springframework.org/schema/batch

http://www.springframework.org/schema/batch/spring-batch-2.0.xsd">

    <beans:import resource="applicationContext.xml"/>

<job id="helloWorldJob" job-repository="jobRepository">
	<step id="step1">
		<tasklet ref="helloWorldTasklet" />
	</step>
</job>

<beans:bean name="helloWorldTasklet" class="com.test.HelloWorldTasklet"/>

<!--
To run the job from the command line type the following:
mvn exec:java -Dexec.mainClass=org.springframework.batch.core.launch.support.CommandLineJobRunner -Dexec.args="simpleJob.xml helloWorldJob"
 -->
</beans:beans>

Define the Tasklet

The following Class file represents a Tasklet that prints hello world to the screen.

src/main/java/com/test/HelloWorldTasklet.java

package com.test;

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 HelloWorldTasklet implements Tasklet {

	public RepeatStatus execute(StepContribution arg0, ChunkContext arg1)
			throws Exception {
		System.out.println("");
		System.out.println(" XXX XXX           XX      XX             ");
		System.out.println("  X   X             X       X             ");
		System.out.println("  X   X             X       X             ");
		System.out.println("  X   X   XXXXX     X       X     XXXXX   ");
		System.out.println("  XXXXX  X     X    X       X    X     X  ");
		System.out.println("  X   X  XXXXXXX    X       X    X     X  ");
		System.out.println("  X   X  X          X       X    X     X  ");
		System.out.println("  X   X  X     X    X       X    X     X  ");
		System.out.println(" XXX XXX  XXXXX   XXXXX   XXXXX   XXXXX   ");
		System.out.println("                                          ");
		System.out.println("                                          ");
		System.out.println("                                          ");
		System.out.println("                                          ");
		System.out.println(" XXX XXX                   XX        XX   ");
		System.out.println("  X   X                     X         X   ");
		System.out.println("  X   X                     X         X   ");
		System.out.println("  X   X   XXXXX  XXX XX     X     XXXXX   ");
		System.out.println("  X X X  X     X   XX  X    X    X    X   ");
		System.out.println("  X X X  X     X   X        X    X    X   ");
		System.out.println("  X X X  X     X   X        X    X    X   ");
		System.out.println("   X X   X     X   X        X    X    X   ");
		System.out.println("   X X    XXXXX  XXXXX    XXXXX   XXXXXX  ");
		System.out.println("");
		return RepeatStatus.FINISHED;
	}
}

Execute the Job

To run the job from the command line type the following.

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

Deploying the application

The following tutorial describes how to Package and deploy the application as a self contained jar.

Resources

What’s Next?

In the next few articles I plan on describing how to:

  1. Read and write flat files.
  2. Write header and footer records in the output file.
  3. Replace the in-memory database with a HyperSQL Java database so we can have job information persist between job invocations.
  4. Throw an exception in the middle of a large batch job and restart the job execution from the point where it left off.
Advertisements

22 Responses to “Hello World With Spring Batch 2.0.x”


  1. 1 dilip
    March 10, 2010 at 10:51 am

    nice tutorial..works like a charm!!..will surely put this on my blog !!

  2. 2 Sharath Babu C
    April 23, 2010 at 2:11 am

    Nice tutorial to start an app with spring batch

  3. 3 Jayakumar
    May 5, 2010 at 5:16 am

    Good Tutorial..
    How to run this Job without using command line

  4. September 24, 2010 at 1:40 am

    Nice tutorial.It helped me a lot..thanks!

  5. 5 tony
    November 4, 2010 at 6:45 am

    excellent tutorial…

  6. 6 Ram
    March 24, 2011 at 5:17 pm

    thank you so much.
    It is really gr8.

  7. 7 anthalamus
    August 24, 2011 at 3:07 pm

    very useful to me too, thanks ;)

  8. 8 JLA
    September 28, 2011 at 7:38 am

    I had to add one more dependency to the POM for Spring Beans (see below), but aside from that, worked like a charm. Really big help in simply getting a basic Spring Batch app up and running.

    org.springframework
    spring-beans
    ${spring.framework.version}

  9. 9 James White
    October 18, 2011 at 4:39 pm

    Great tutorial series on Spring Batch. I have used before, but am using your tutorials to refresh my knowledge of the framework. keep posting the tutorials. Great job.

  10. November 16, 2011 at 2:05 am

    Hi,

    I tried to convert this project and run as an executable jar, but I am getting the following error

    Caused by: org.xml.sax.SAXParseException: cvc-complex-type.2.4.c: The matching w
    ildcard is strict, but no declaration can be found for element ‘job’.

    Can anyone throw some light on this?

    Regards,
    Chandrasekar V.

  11. 11 tony
    February 2, 2012 at 3:02 am

    This is great sample, followed it and succeed, thanks!

  12. 12 Harsan
    April 9, 2012 at 10:32 am

    Good Job. Very helpful for starters…

  13. 13 JuliusGB
    April 19, 2012 at 7:33 am

    Hi,
    Thanks for the clear tutorial – it worked for me too.

    In addition, this tutorial isn’t specific to any IDE, something very rare nowadays. How many tutorials are so coupled with a specific IDE that they become unusable to those who use other IDEs (or notepad).

  14. 14 Raj
    April 30, 2012 at 9:03 am

    Thank..it really helped me. Earlier i was tried runnig the command..
    “java -jar hello-world-0.0.1.SNAPSHOT.jar jobs/helloWorld.xml helloWorldJob” from the target folder where the jar existed but it was throwing the infamous ClassNotFoundException….

    Your command from maven ran my hello world program…Do you have an idea as to what is the problem with the earlier command.

  15. 16 bob
    January 2, 2013 at 10:49 am

    Nice work – I found several other “Simple” Spring Batch examples on the web but this was the simplest one, and the only one that worked first time without modification.


Leave a Reply

Please log in using one of these methods to post your comment:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s


Enter your email address to subscribe to this blog and receive notifications of new posts by email.

Join 74 other followers

February 2010
S M T W T F S
« Jan   Mar »
 123456
78910111213
14151617181920
21222324252627
28  

Blog Stats

  • 801,304 hits

%d bloggers like this: