`

Spring Batch HelloWorld 例子

阅读更多

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 Step s. 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

JobLauncher s 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/beans http://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>
<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;
  }
}
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/beans http://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>
<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 .

分享到:
评论
3 楼 我可梦 2013-08-22  
spring batch管理平台,试用环境:

http://s-77347.gotocdn.com/

欢迎大家提出意见。

2 楼 我可梦 2013-08-16  
试试用spring batch管理平台吧,就不用这么麻烦深入了解batch后,才会使用呢。

http://www.honghaifang.com/archives/1444
1 楼 windcloud1986 2010-12-02  
这个是如何触发的,怎么配置?

相关推荐

    SpringBatch-HelloWorld

    SpringBatch Tasklet sample

    SpringBatch+Spring+Mybatis+MySql (spring batch 使用jar)

    Spring Batch是一个轻量级的,完全面向Spring的批处理框架,可以应用于企业级大量的数据处理系统。Spring Batch以POJO和大家熟知的Spring框架为基础,使开发者更容易的访问和利用企业级服务。Spring Batch可以提供...

    Spring Batch in Action英文pdf版

    Spring Batch是一个开源的轻量级、全面的批处理框架,它是为了解决企业应用中的大规模数据处理需求而设计的。Spring Batch in Action是一本专注于Spring Batch框架的书籍,由Arnaud Cogoluègnes、Thierry Templier...

    Spring Boot整合Spring Batch,实现批处理

    在Java开发领域,Spring Boot和Spring Batch的整合是构建高效批处理系统的一种常见方式。Spring Boot以其简洁的配置和快速的启动能力深受开发者喜爱,而Spring Batch作为Spring框架的一部分,专注于批量处理任务,...

    The Definitive Guide to Spring Batch, 2nd Edition.epub

    The Definitive Guide to Spring Batch takes you from the “Hello, World!” of batch processing to complex scenarios demonstrating cloud native techniques for developing batch applications to be run on...

    quartz整合springbatch动态集群定时实现mysql参考

    Quartz和Spring Batch是两种非常重要的Java开源框架,它们在企业级应用开发中扮演着重要角色。Quartz主要用于任务调度,而Spring Batch则专注于批量处理。在这个“quartz_springbatch_dynamic”项目中,我们将看到...

    springbatch 详解PDF附加 全书源码 压缩包

    **Spring Batch 深度解析** Spring Batch 是一个强大的、全面的批处理框架,由 Spring 社区开发,旨在简化企业级应用中的批量数据处理任务。这个框架提供了一种标准的方式来处理大量的数据输入和输出,使得开发者...

    Spring Batch批处理框架

    Spring Batch是一个开源的轻量级批处理框架,它提供了一整套可复用的组件,用于构建健壮且高效的批处理应用程序。由于信息给定的【部分内容】并没有提供实际的技术细节,因此我将基于Spring Batch框架本身,详细介绍...

    [原创]Spring Batch 示例程序

    Spring Batch 是一个强大的Java框架,专门用于处理批量数据处理任务。在给定的"Spring Batch 示例程序"中,我们可以深入探讨这个框架的核心概念和在实际应用中的使用方式。该示例程序采用的是Spring 3作为基础框架,...

    Spring AMQP hello world

    通过这个简单的“Hello World”例子,你已经初步了解了Spring AMQP的基本工作流程。实际项目中,你可以根据需求创建更复杂的队列、交换机和绑定,实现更高级的功能,如发布/订阅模式、延迟消息、死信队列等。 ...

    基于Spring Batch的大数据量并行处理

    ### 基于Spring Batch的大数据量并行处理 #### 概述 Spring Batch是一款用于高效处理大量数据的开源框架,特别适用于批处理任务。它由Spring Source与Accenture合作开发,结合了双方在批处理架构和技术上的优势,...

    Spring Batch API(Spring Batch 开发文档).CHM

    Spring Batch API(Spring Batch 开发文档).CHM。 官网 Spring Batch API,Spring Batch 开发文档

    spring-batch包

    Spring Batch 是一个强大的、全面的批处理框架,用于处理大量数据的处理任务。它由 Spring 框架提供支持,因此具有高度的可配置性和可扩展性,适用于各种企业级应用。Spring Batch 4.0.0 版本是该框架的一个重要版本...

    springBoot+springBatch批量处理数据demo

    SpringBoot和SpringBatch是两个非常重要的Java开发框架,它们在企业级应用开发中扮演着重要角色。SpringBoot简化了Spring应用程序的配置和启动过程,而SpringBatch则专注于批处理任务,提供了一套全面且可扩展的解决...

    Spring batch in action

    Spring Batch是一本介绍如何使用Spring Batch框架来构建批处理应用程序的专业书籍。在软件行业中,随着各种趋势的发展,例如基于Web的应用、面向服务的架构(SOA)以及事件驱动的应用,批处理应用程序虽然存在已久,...

    spring Batch实现数据库大数据量读写

    Spring Batch 是一个强大的、可扩展的Java框架,专门用于处理批量数据处理任务,包括大量数据库数据的读取、处理和写入。它被设计为在企业级应用中处理大规模、高吞吐量的工作负载。本篇文章将深入探讨如何利用...

    SpringBatch-DataMigration SpringBatch数据迁移项目

    mybatis、springBatch、mysql、quartz、spring、springMVC 部署说明: 本项目为两个数据库,由一个数据库的表向另外一个数据库的表做数据迁移,其中数据库脚本在:/src/main/resources/sql/下面(其中data_rep中的表...

Global site tag (gtag.js) - Google Analytics