Spring Batch 简明教程

Spring Batch - Quick Guide

Spring Batch - Overview

Batch processing 是处理模式,此模式涉及在用户不进行交互的情况下执行一系列自动化复杂任务。批处理处理批量数据,且运行很长时间。

需要处理大量数据以执行涉及操作的多个企业应用程序 −

  1. 基于时间的事件,例如定期计算。

  2. 在较大的数据集上重复处理的定期应用程序。

  3. 处理和验证以事务方式提供的数据的应用程序。

因此,批处理用于企业应用程序以执行此类事务。

What is Spring Batch

Spring Batch 是一款 lightweight framework ,此类用于开发企业应用程序中使用的 Batch Applications

除了批量处理外,此框架还提供以下功能 −

  1. Including logging and tracing

  2. Transaction management

  3. Job processing statistics

  4. Job restart

  5. Skip and Resource management

你还可以使用其分区技术来扩展 Spring Batch 应用程序。

Features of Spring Batch

以下是 Spring Batch 的著名功能 −

  1. Flexibility − Spring Batch应用程序灵活。您只需更改一个XML文件即可改变应用程序中处理的顺序。

  2. Maintainability − Spring Batch应用程序易于维护。Spring Batch作业包括步骤,并且可以解耦、测试和更新每个步骤,而不会影响其他步骤。

  3. Scalability − 使用分区技术,您可以扩展Spring Batch应用程序。这些技术允许您−并行执行作业的步骤。并行执行一个线程。

  4. Reliability − 在发生任何故障的情况下,您可以通过解耦步骤从发生故障的地方重新启动作业。

  5. Support for multiple file formats − Spring Batch为大量的读取器和写入器提供支持,例如XML、平面文件、CSV、MYSQL、Hibernate、JDBC、Mongo、Neo4j等。

  6. Multiple ways to launch a job − 您可以使用Web应用程序、Java程序、命令行等启动Spring Batch作业。

除了这些之外,Spring Batch应用程序支持−

  1. Automatic retry after failure.

  2. 在批处理执行期间和完成批处理后跟踪状态和统计信息。

  3. To run concurrent jobs.

  4. 诸如日志记录、资源管理、跳过和重新启动处理的服务。

Spring Batch - Environment

在本章中,我们将解释如何将 Spring Batch 环境设置到 Eclipse IDE 中。在继续安装前,确保您已在您的系统中安装 Eclipse。如果没有,请在您的系统中下载并安装 Eclipse。

如需了解 Eclipse 的更多信息,请参考我们的 Eclipse Tutorial.

Setting Spring Batch on Eclipse

按照以下步骤在 Eclipse 上设置 Spring Batch 环境。

Step 1 − 安装 Eclipse,然后打开一个新项目,如以下屏幕截图所示。

new project

Step 2 − 创建一个样本 Spring Batch 项目,如下所示。

project name

Step 3 − 右键单击项目,然后按以下所示将其转换为一个 Maven 项目。将其转换为 Maven 项目后,将提供 Pom.xml ,您需要在其中提及必需的依赖项。然后,将 jar 文件自动下载到您的项目中。

configure

Step 4 − 现在,在项目的 pom.xml 中,复制并粘贴以下内容(spring 批处理应用程序的依赖项),然后刷新项目。

<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.tutorialspoint</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>5.3.14</spring.version>
      <spring.batch.version>4.3.4</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>

Spring Batch - Architecture

以下是 Spring Batch 架构的示意图。如此图所示,此架构包含三个主要组件,即 Application, Batch CoreBatch Infrastructure

architecture

Application − 此组件包含我们使用 Spring Batch 框架编写的全部作业和代码。

Batch Core − 此组件包含控制和启动批处理作业所需的所有 API 类。

Batch Infrastructure − 此组件包含应用程序和批处理核心组件使用的读取器、编写器和服务。

Components of Spring Batch

下图显示了 Spring Batch 的不同组件以及它们如何相互连接。

components

Job

在 Spring Batch 应用程序中,作业是要执行的批处理。它从开始到结束连续运行。此作业进一步细分为步骤(或作业包含步骤)。

我们将在 Spring Batch 中使用 XML 文件或 Java 类配置作业。以下是 Spring Batch 中对作业的 XML 配置。

<job id = "jobid">
   <step id = "step1" next = "step2"/>
   <step id = "step2" next = "step3"/>
   <step id = "step3"/>
</job>

批处理作业是在 <job></job> 标签中配置的。它有一个名为 id 的属性。在这些标签内,我们定义步骤的定义和顺序。

Restartable − 一般来说,当一个作业正在运行,并且我们尝试再次启动它,这被认为是 restart ,并且它将再次启动。为避免此问题,您需要将 restartable 值设置为 false ,如下所示。

<job id = "jobid" restartable = "false" >

</job>

Step

一个 step 是一个作业的独立部分,其中包含定义和执行作业(其部分)所需的信息。

如该图所示,每一步都由一个 ItemReader、ItemProcessor(可选)和一个 ItemWriter 组成。 A job may contain one or more steps

Readers, Writers, and Processors

一个 item reader 从特定来源读取数据到一个 Spring Batch应用程序中,而 item writer 将数据从 Spring Batch 应用程序写入到特定目的地中。

一个 Item processor 是一个包含处理从 Spring Batch 读入数据的处理器代码的类。如果应用程序读取 "n" 记录,那么处理器中的代码将被执行在每个记录上。

当未给定阅读器和编写器时,一个 tasklet 充当 SpringBatch 的处理器。它只处理一个单一任务。例如,如果我们正在编写一个作业,其中有一个简单的步骤,我们从 MySQL 数据库中读取数据并对其进行处理,然后将其写入文件(扁平文件),那么我们的步骤使用 −

  1. 一个 reader ,从 MySQL 数据库读取。

  2. 一个 writer ,写入一个扁平文件。

  3. 一个 custom processor ,按照我们的希望处理数据。

<job id = "helloWorldJob">
   <step id = "step1">
      <tasklet>
         <chunk reader = "mysqlReader" writer = "fileWriter"
            processor = "CustomitemProcessor" ></chunk>
      </tasklet>
   </step>
</ job>

Spring Batch 提供了一个 readerswriters 的长列表。使用这些预定义的类,我们能够为它们定义 Bean。我们将在以后的章节中详细讨论 readerswriters

JobRepository

Spring Batch 中的作业存储库为 JobLauncher、Job 和 Step 实现提供创建、检索、更新和删除 (CRUD) 操作。我们将在一个 XML 文件中定义一个作业存储库,如下所示。

<job-repository id = "jobRepository"/>

除了 id ,还有一些额外的选项(可选)。以下是带有所有选项及其默认值的作业存储库配置。

<job-repository id = "jobRepository"
   data-source = "dataSource"
   transaction-manager = "transactionManager"
   isolation-level-for-create = "SERIALIZABLE"
   table-prefix = "BATCH_"
   max-varchar-length = "1000"/>

In-Memory Repository − 如果您不想在数据库中保留 Spring Batch 的域对象,您可以按照以下所示配置 jobRepository 的内存版本。

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

JobLauncher

JobLauncher 是一个使用 given set of parameters 启动 Spring Batch 作业的接口。 SampleJoblauncher 是实现 JobLauncher 接口的类。以下是 JobLauncher 的配置。

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

JobInstance

一个 JobInstance 表示一个作业的逻辑运行;它是在我们运行作业时创建的。每个作业实例通过作业的名称和在运行时传递给它的参数进行区分。

如果一个 JobInstance 执行失败,相同的 JobInstance 可以再次执行。因此,每个 JobInstance 可以有多个作业执行。

JobExecution and StepExecution

JobExecution 和 StepExecution 是一个作业/步骤执行的表示。它们包含作业/步骤的运行信息,诸如开始时间(作业/步骤)、结束时间(作业/步骤)。

Spring Batch - Application

本教程中几乎所有示例都包含以下文件 −

  1. Configuration file (XML file)

  2. Tasklet/processor (Java class)

  3. 带 setter 和 getter 的 Java 类(Java 类(bean))

  4. Mapper class (Java class)

  5. Launcher class (Java class)

Configuration File

配置文件 (XML) 包含以下 −

  1. jobstep 定义。

  2. 定义 readerswriters 的 bean。

  3. 定义 JobLauncher、JobRepository、Transaction Manager 和 Data Source 等组件。

在我们的示例中,为了更好的理解,我们将其分为两个文件,即 job.xml 文件(定义 job、step、reader 和 writer)和 context.xml 文件(job launcher、job repository、transaction manager 和 data source)。

Mapper Class

Mapper 类根据 reader 来实现 row mapperfield set mapper 等接口。它包含从 reader 获取数据并将它设置为带 settergetter 方法的 Java 类(Java Bean)的代码。

Java Bean Class

settersgetters 的 Java 类(Java bean)表示具有多个值的数据。它作为一个帮助类。我们通过该类的对象的形式传递数据从一个组件(reader、writer、processor)到另一个组件。

Tasklet/processor

Tasklet/processor 类包含 Spring Batch 应用程序的处理代码。processor 是一个接受包含读取数据、处理它并以对象形式返回处理数据的对象(in the form object) 的类。

Launcher class

该类(App.java)包含启动 Spring Batch 应用程序的代码。

application

Spring Batch - Configuration

在编写Spring Batch应用程序时,我们将使用Spring Batch命名空间中提供的XML标记配置作业、步骤、JobLauncher、JobRepository、事务管理器、读取器和写入器。因此,您需要像下面显示的那样在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/bean
   http://www.springframework.org/schema/beans/spring-beans-3.2.xsd">

在以下部分中,我们将讨论Spring Batch命名空间中可用的各种标记、它们的属性和示例。

Job

此标记用于定义/配置SpringBatch的作业。它包含一组步骤,并且可以使用JobLauncher启动它。

此标记具有如下所列的2个属性−

S.No

Attribute & Description

1

Id 它是作业的ID,此属性必须指定值。

2

restartable 这是用于指定作业是否可重新启动的属性。此属性是可选的。

以下是SpringBatch作业的XML配置。

<job id = "jobid" restartable = "false" >
   . . . . . . . .
   . . . . . . . .
   . . . . . . . . // Step definitions
</job>

Step

此标记用于定义/配置SpringBatch作业的步骤。它具有以下三个属性−

S.No

Attribute & Description

1

Id 它是作业的ID,此属性必须指定值。

2

next 它表示的基本上是指定下一步的快捷方式。

3

parent 用来指定父级 bean 的名称,该 bean 所在的位置就是配置所应该继承的位置。

以下内容为 SpringBatch 步骤的 XML 配置。

<job id = "jobid">
   <step id = "step1" next = "step2"/>
   <step id = "step2" next = "step3"/>
   <step id = "step3"/>
</job>

Chunk

此标签用来定义/配置 tasklet 的一部分。它有以下四个属性:

S.No

Attribute & Description

1

reader 它表示读取器 bean 的名称。它接受类型 org.springframework.batch.item.ItemReader 的值。

2

writer 它表示读取器 bean 的名称。它接受类型 org.springframework.batch.item.ItemWriter 的值。

3

processor 它表示读取器 bean 的名称。它接受类型 org.springframework.batch.item.ItemProcessor 的值。

4

commit-interval 用来指定在提交事务前要处理的项目的个数。

以下内容为 SpringBatch 的部分内容 XML 配置。

<batch:step id = "step1">
   <batch:tasklet>
      <batch:chunk reader = "xmlItemReader"
         writer = "mysqlItemWriter" processor = "itemProcessor" commit-interval = "10">
      </batch:chunk>
   </batch:tasklet>
</batch:step>

JobRepository

JobRepository Bean 可用于通过关系数据库配置一个 JobRepository。这个 bean 与类型为 org.springframework.batch.core.repository.JobRepository 的类关联。

S.No

Attribute & Description

1

dataSource 用来指定定义数据源的 bean 的名称。

2

transactionManager 用来指定 bean 的名称,该 bean 会定义一个事务管理器。

3

databaseType 它指定在作业存储库所用的关系数据库类型。

JobRepository 的配置范例如下。

<bean id = "jobRepository"
   class = "org.springframework.batch.core.repository.support.JobRepositoryFactoryBean">
   <property name = "dataSource" ref = "dataSource" />
   <property name = "transactionManager" ref="transactionManager" />
   <property name = "databaseType" value = "mysql" />
</bean>

JobLauncher

JobLauncher Bean 可用于配置 JobLauncher。它与类 org.springframework.batch.core.launch.support.SimpleJobLauncher 关联 (在我们的程序中)。这个 bean 有一个名为 jobrepository 的属性,用于指定定义 jobrepository 的 bean 的名称。

JobLauncher 的配置范例如下。

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

TransactionManager

TransactionManager Bean 可用于通过关系数据库配置 TransactionManager。这个 bean 与类型为 org.springframework.transaction.platform.TransactionManager 的类关联。

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

DataSource

Datasource Bean 用来配置 Datasource 。这个 Bean 与类型为 org.springframework.jdbc.datasource.DriverManagerDataSource 的类关联。

S.No

Attribute & Description

1

driverClassName 它指定与数据库连接时所用的驱动程序的类别名称。

2

url 这指定数据库的网址

3

username 这指定用于连接到数据库的用户名

4

password 这指定用于连接到数据库的密码

以下为 datasource 的示例配置

<bean id = "dataSource"
   class = "org.springframework.jdbc.datasource.DriverManagerDataSource">
   <property name = "driverClassName" value = "com.mysql.jdbc.Driver" />
   <property name = "url" value = "jdbc:mysql://localhost:3306/details" />
   <property name = "username" value = "myuser" />
   <property name = "password" value = "password" />
</bean>

Spring Batch - Readers, Writers & Processors

Item Reader 从特定源读取数据到 Spring Batch 应用程序,而 Item Writer 将数据从 Spring Batch 应用程序写入到特定目标。

Item processor 是一个包含处理代码的类,该代码处理读入到 Spring Batch 中的数据。如果应用程序读取 n 条记录,则处理器中的代码将在每条记录上执行。

chunktasklet 的子元素。它用于执行读取、写入和处理操作。我们可以使用该元素在步骤中配置读取器、写入器和处理器,如下所示。

<batch:job id = "helloWorldJob">
   <batch:step id = "step1">
      <batch:tasklet>
         <batch:chunk reader = "cvsFileItemReader" writer = "xmlItemWriter"
            processor = "itemProcessor" commit-interval = "10">
         </batch:chunk>
      </batch:tasklet>
   </batch:step>
</batch:job>

Spring Batch 提供读取器和写入器以读取和写入各种文件系统/数据库的数据,例如 MongoDB、Neo4j、MySQL、XML、扁平文件、CSV 等。

要将读取器包含在应用程序中,您需要为该读取器定义一个 bean,为 bean 中的所有必需属性提供值,并将该 bean 的 id 作为 reader 的属性值传递(对 writer 也一样)。

ItemReader

它是读取数据的步骤(批量处理的步骤)的实体。ItemReader 每次读取一项。Spring Batch 提供了一个接口 ItemReader 。所有 readers 都实现了此接口。

以下是 Spring Batch 提供的用于从各种来源读取数据的一些预定义 ItemReader 类。

Reader

Purpose

FlatFIleItemReader

从平面文件中读取数据。

StaxEventItemReader

从 XML 文件中读取数据。

StoredProcedureItemReader

从数据库的存储过程中读取数据。

JDBCPagingItemReader

从关系数据库中读取数据。

MongoItemReader

从 MongoDB 中读取数据。

Neo4jItemReader

从 Neo4jItemReader 中读取数据。

我们需要通过创建 bean 来配置 ItemReaders 。下面是 StaxEventItemReader 的一个示例,它从 XML 文件中读取数据。

<bean id = "mysqlItemWriter"
   class = "org.springframework.batch.item.xml.StaxEventItemWriter">
   <property name = "resource" value = "file:xml/outputs/userss.xml" />
   <property name = "marshaller" ref = "reportMarshaller" />
   <property name = "rootTagName" value = "Tutorial" />
</bean>

<bean id = "reportMarshaller"
   class = "org.springframework.oxm.jaxb.Jaxb2Marshaller">
   <property name = "classesToBeBound">
      <list>
         <value>Tutorial</value>
      </list>
   </property>
</bean>

如您所见,在配置时,我们需要指定所需读取器的相应类名,并且我们需要为所有必需属性提供值。

ItemWriter

它是批量处理 step 的元素,用于写入数据。ItemWriter 每次写入一项。Spring Batch 提供了一个接口 ItemWriter 。所有写入器都实现了此接口。

以下是 Spring Batch 提供的用于从各种来源读取数据的一些预定义 ItemWriter 类。

Writer

Purpose

FlatFIleItemWriter

将数据写入平面文件。

StaxEventItemWriter

将数据写入 XML 文件。

StoredProcedureItemWriter

将数据写入数据库的存储过程。

JDBCPagingItemWriter

将数据写入关系数据库。

MongoItemWriter

将数据写入 MongoDB。

Neo4jItemWriter

将数据写入 Neo4j。

同样,我们需要通过创建 Bean 来配置 ItemWriter。下面是一个将数据写入 MySQL 数据库的 JdbcCursorItemReader 的示例。

<bean id = "dbItemReader"
   class = "org.springframework.batch.item.database.JdbcCursorItemReader" scope = "step">
   <property name = "dataSource" ref = "dataSource" />
   <property name = "sql" value = "select * from tutorialsdata" />
   <property name = "rowMapper">
      <bean class = "TutorialRowMapper" />
   </property>
</bean>

Item Processor

ItemProcessor − 使用ItemProcessor处理数据。当给定的项无效时,它返回 null ,否则它将处理给定的项并返回处理后的结果。接口 ItemProcessor<I,O> 表示处理器。

Tasklet class − 当未给定 readerwriter 时,Tasklet 会充当 SpringBatch 的处理器。它只处理单一任务。

我们可以通过实现包 org.springframework.batch.item.ItemProcessor 的接口 ItemProcessor 来定义一个自定义项处理器。此 ItemProcessor 类接受一个对象并处理数据,然后将处理后的数据作为另一个对象返回。

在批处理中,如果读取 "n" 记录或数据元素,则对于每条记录,它将读取数据、处理数据并将数据写入编写器。要处理数据,它依赖于传递的处理器。

例如,假设你已编写代码来加载特定 PDF 文档、创建新页面、以表格形式将数据项写入 PDF。如果你执行此应用程序,它会从 XML 文档中读取所有数据项,将它们存储在 MySQL 数据库中,并以单个页面形式将它们打印在给定的 PDF 文档中。

Example

以下是示例 ItemProcessor 类。

import org.springframework.batch.item.ItemProcessor;

public class CustomItemProcessor implements ItemProcessor<Tutorial, Tutorial> {

   @Override
   public Tutorial process(Tutorial item) throws Exception {
      System.out.println("Processing..." + item);
      return item;
   }
}

Spring Batch - Basic Application

本章向你展示了基本的 Spring Batch 应用程序。它会简单地执行一个 tasklet 来显示一条消息。

我们的 Spring Batch 应用程序包含以下文件 -

  1. Configuration file - 这是一个 XML 文件,在其中我们定义了工作和工作的步骤。(如果应用程序也涉及读者和作者,则 readerswriters 的配置也包括在这个文件中。)

  2. Context.xml - 在这个文件中,我们将定义诸如工作存储库、工作启动器和事务管理器这样的 bean。

  3. Tasklet class - 在这个类中,我们将编写处理代码工作(在这种情况下,它会显示一条简单消息)

  4. Launcher class - 在这个类中,我们将通过运行工作启动器来启动批处理应用程序。

jobConfig.xml

以下为我们示例 Spring Batch 应用程序的配置文件

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

Context.xml

以下为我们 Spring Batch 应用程序的 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>

Tasklet.java

以下是显示简单消息的 Tasklet 类

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;
   }
}

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());
   }
}

在执行时,以上 SpringBatch 程序将生成以下输出 −

Apr 24, 2017 4:40:54 PM org.springframework.context.support.AbstractApplicationContext prepareRefresh
INFO:Refreshing org.springframework.context.support.ClassPathXmlApplicationContext@2ef1e4fa: startup date [Mon Apr 24 16:40:54 IST 2017]; root of context hierarchy
Apr 24, 2017 4:40:54 PM org.springframework.beans.factory.xml.XmlBeanDefinitionReader loadBeanDefinitions INFO: Loading XML bean definitions
Apr 24, 2017 4:40:54 PM org.springframework.beans.factory.xml.XmlBeanDefinitionReader loadBeanDefinitions
INFO: Loading XML bean definitions
Apr 24, 2017 4:40:54 PM org.springframework.beans.factory.support.DefaultListableBeanFactory preInstantiateSingletons
Apr 24, 2017 4:40:55 PM org.springframework.batch.core.launch.support.SimpleJobLauncher afterPropertiesSet
INFO: No TaskExecutor has been set, defaulting to synchronous executor.
Apr 24, 2017 4:40:55 PM org.springframework.batch.core.launch.support.SimpleJobLauncher$1 run
INFO: Job: [FlowJob: [name=helloWorldJob]] launched with the following parameters: [{}]
Apr 24, 2017 4:40:55 PM org.springframework.batch.core.job.SimpleStepHandler handleStep INFO: Executing step: [step1]
Hello This is a sample example of spring batch
Apr 24, 2017 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

Spring Batch - XML to MySQL

在本章中,我们将创建一个使用 XML 读取器和 MySQL 写入器的 Spring Batch 应用程序

Reader − 我们在应用程序中使用的读取器是 StaxEventItemReader 以从 XML 文档读取数据

以下为我们在本应用程序中使用的输入 XML 文档。此文档包含详细记录指定教程 ID、教程作者、教程标题、提交日期、教程图标和教程描述等详细信息的数据记录

<?xml version="1.0" encoding="UTF-8"?>
<tutorials>
   <tutorial>
      <tutorial_id>1001</tutorial_id>
      <tutorial_author>Sanjay</tutorial_author>
      <tutorial_title>Learn Java</tutorial_title>
      <submission_date>06-05-2007</submission_date>
      <tutorial_icon>https://www.tutorialspoint.com/java/images/java-minilogo.jpg</tutorial_icon>
      <tutorial_description>Java is a high-level programming language originally
         developed by Sun Microsystems and released in 1995.
         Java runs on a variety of platforms.
         This tutorial gives a complete understanding of Java.');</tutorial_description>
   </tutorial>

   <tutorial>
      <tutorial_id>1002</tutorial_id>
      <tutorial_author>Abdul S</tutorial_author>
      <tutorial_title>Learn MySQL</tutorial_title>
      <submission_date>19-04-2007</submission_date>
      <tutorial_icon>https://www.tutorialspoint.com/mysql/images/mysql-minilogo.jpg</tutorial_icon>
      <tutorial_description>MySQL is the most popular
         Open Source Relational SQL database management system.
         MySQL is one of the best RDBMS being used for developing web-based software applications.
         This tutorial will give you quick start with MySQL
         and make you comfortable with MySQL programming.</tutorial_description>
   </tutorial>

   <tutorial>
      <tutorial_id>1003</tutorial_id>
      <tutorial_author>Krishna Kasyap</tutorial_author>
      <tutorial_title>Learn JavaFX</tutorial_title>
      <submission_date>06-07-2017</submission_date>
      <tutorial_icon>https://www.tutorialspoint.com/javafx/images/javafx-minilogo.jpg</tutorial_icon>
      <tutorial_description>JavaFX is a Java library used to build Rich Internet Applications.
         The applications developed using JavaFX can run on various devices
         such as Desktop Computers, Mobile Phones, TVs, Tablets, etc.
         This tutorial, discusses all the necessary elements of JavaFX that are required
         to develop effective Rich Internet Applications</tutorial_description>
   </tutorial>
</tutorials>

Writer − 我们在应用程序中使用的 writerJdbcBatchItemWriter 以将数据写入 MySQL 数据库。假设我们在名为 "details" 的数据库中创建了 MySQL 中的一个表

CREATE TABLE details.TUTORIALS(
   tutorial_id int(10) NOT NULL,
   tutorial_author VARCHAR(20),
   tutorial_title VARCHAR(50),
   submission_date VARCHAR(20),
   tutorial_icon VARCHAR(200),
   tutorial_description VARCHAR(1000)
);

Processor − 我们在应用程序中使用的处理器是一个自定义处理器,它在 PDF 文档上输出每条记录的数据。

在批处理中,如果读取 "n" 记录或数据元素,那么对于每条记录,它将读取数据,处理它,然后在写入器中写入数据。要处理数据,它会中继到已传递的处理器。在本例中,在自定义的处理器类中,我们编写的代码能够加载特定的 PDF 文档,创建一个新页面,将数据项以表格格式写入 PDF。

最后,如果你执行此应用程序,它将从 XML 文档读取所有数据项,将它们存储在 MySQL 数据库中,并以单独的页面在给定的 PDF 文档中打印它们。

jobConfig.xml

以下为我们示例 Spring Batch 应用程序的配置文件。在此文件中,我们将定义作业和步骤。除了这些之外,我们还将定义 ItemReader、ItemProcessor 和 ItemWriter 的 Bean。(在这里,我们将它们分别与其类关联起来,并传递必需的属性值来配置它们。)

<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"
   xmlns:util = "http://www.springframework.org/schema/util"
   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
      http://www.springframework.org/schema/util
      http://www.springframework.org/schema/util/spring-util-3.0.xsd ">

   <import resource = "../jobs/context.xml" />

   <bean id = "itemProcessor" class = "CustomItemProcessor" />
   <batch:job id = "helloWorldJob">
      <batch:step id = "step1">
         <batch:tasklet>
            <batch:chunk reader = "xmlItemReader" writer = "mysqlItemWriter" processor = "itemProcessor">
            </batch:chunk>
         </batch:tasklet>
      </batch:step>
   </batch:job>

   <bean id = "xmlItemReader"
      class = "org.springframework.batch.item.xml.StaxEventItemReader">
      <property name = "fragmentRootElementName" value = "tutorial" />
      <property name = "resource" value = "classpath:resources/tutorial.xml" />
      <property name = "unmarshaller" ref = "customUnMarshaller" />
   </bean>

   <bean id = "customUnMarshaller" class = "org.springframework.oxm.xstream.XStreamMarshaller">
      <property name = "aliases">
         <util:map id = "aliases">
            <entry key = "tutorial" value = "Tutorial" />
         </util:map>
      </property>
   </bean>
   <bean id = "mysqlItemWriter" class = "org.springframework.batch.item.database.JdbcBatchItemWriter">
      <property name = "dataSource" ref = "dataSource" />
      <property name = "sql">
         <value>
            <![CDATA[insert into details.tutorials (tutorial_id, tutorial_author, tutorial_title,
               submission_date, tutorial_icon, tutorial_description)
               values (:tutorial_id, :tutorial_author, :tutorial_title, :submission_date,
               :tutorial_icon, :tutorial_description);]]>
         </value>
      </property>

      <property name = "itemSqlParameterSourceProvider">
         <bean class = "org.springframework.batch.item.database.BeanPropertyItemSqlParameterSourceProvider" />
      </property>
   </bean>
</beans>

Context.xml

以下是我们 Spring Batch 应用程序的 context.xml 。在该文件中,我们将定义 Bean,如 Job 存储库、Job 启动器和事务管理器。

<beans xmlns = "http://www.springframework.org/schema/beans"
   xmlns:jdbc = "http://www.springframework.org/schema/jdbc"
   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
      http://www.springframework.org/schema/jdbc
      http://www.springframework.org/schema/jdbc/spring-jdbc-3.2.xsd">

   <!-- stored job-meta in database -->
   <bean id = "jobRepository"
      class = "org.springframework.batch.core.repository.support.JobRepositoryFactoryBean">
      <property name = "dataSource" ref = "dataSource" />
      <property name = "transactionManager" ref = "transactionManager" />
      <property name = "databaseType" value = "mysql" />
   </bean>

   <bean id = "transactionManager"
   class = "org.springframework.batch.support.transaction.ResourcelessTransactionMana ger" />
   <bean id = "jobLauncher"
      class = "org.springframework.batch.core.launch.support.SimpleJobLauncher">
      <property name = "jobRepository" ref = "jobRepository" />
   </bean>

   <!-- connect to MySQL database -->
   <bean id = "dataSource"
      class = "org.springframework.jdbc.datasource.DriverManagerDataSource">
      <property name = "driverClassName" value = "com.mysql.jdbc.Driver" />
      <property name = "url" value = "jdbc:mysql://localhost:3306/details" />
      <property name = "username" value = "myuser" />
      <property name = "password" value = "password" />
   </bean>

   <!-- create job-meta tables automatically -->
   <jdbc:initialize-database data-source = "dataSource">
      <jdbc:script location = "org/springframework/batch/core/schema-drop-mysql.sql"/>
      <jdbc:script location = "org/springframework/batch/core/schema-mysql.sql"/>
   </jdbc:initialize-database>
</beans>

CustomItemProcessor.java

以下为 processor 类。在此类中,我们编写应用程序中的处理代码。在这里,我们加载 PDF 文档,创建一个新页面,创建一个表,并为表中的每条记录插入以下的值:教程 ID、教程名称、作者、提交日期。

import java.io.File;
import java.io.IOException;

import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.pdmodel.PDPage;
import org.apache.pdfbox.pdmodel.PDPageContentStream;
import org.apache.pdfbox.pdmodel.font.PDType1Font;
import org.springframework.batch.item.ItemProcessor;

public class CustomItemProcessor implements ItemProcessor<Tutorial, Tutorial> {

   public static void drawTable(PDPage page, PDPageContentStream contentStream,
      float y, float margin, String[][] content) throws IOException {
      final int rows = content.length;
      final int cols = content[0].length;
      final float rowHeight = 50;
      final float tableWidth = page.getMediaBox().getWidth()-(2*margin);
      final float tableHeight = rowHeight * rows;
      final float colWidth = tableWidth/(float)cols;
      final float cellMargin=5f;

      // draw the rows
      float nexty = y ;
      for (int i = 0; i <= rows; i++) {
         contentStream.drawLine(margin,nexty,margin+tableWidth,nexty);
         nexty-= rowHeight;
      }

      //draw the columns
      float nextx = margin;
      for (int i = 0; i <= cols; i++) {
         contentStream.drawLine(nextx,y,nextx,y-tableHeight);
         nextx += colWidth;
      }

      // now add the text
      contentStream.setFont(PDType1Font.HELVETICA_BOLD,12);

      float textx = margin+cellMargin;
      float texty = y-15;
      for(int i = 0; i < content.length; i++){
         for(int j = 0 ; j < content[i].length; j++){
            String text = content[i][j];
            contentStream.beginText();
            contentStream.moveTextPositionByAmount(textx,texty);
            contentStream.drawString(text);
            contentStream.endText();
            textx += colWidth;
         }

         texty-=rowHeight;
         textx = margin+cellMargin;
      }
   }

   @Override
   public Tutorial process(Tutorial item) throws Exception {
      System.out.println("Processing..." + item);

      // Creating PDF document object
      PDDocument doc = PDDocument.load(new File("C:/Examples/test.pdf"));

      // Creating a blank page
      PDPage page = new PDPage();
      doc.addPage( page );
      PDPageContentStream contentStream =  new PDPageContentStream(doc, page);

      String[][] content = {{"Id",""+item.getTutorial_id()},
      {"Title", item.getTutorial_title()},
      {"Authour", item.getTutorial_author()},
      {"Submission Date", item.getSubmission_date()}} ;
      drawTable(page, contentStream, 700, 100, content);

      contentStream.close();
      doc.save("C:/Examples/test.pdf" );
      System.out.println("Hello");
      return item;
   }
}

TutorialFieldSetMapper.java

以下是将数据设置为 Tutorial 类的 ReportFieldSetMapper 类。

import org.springframework.batch.item.file.mapping.FieldSetMapper;
import org.springframework.batch.item.file.transform.FieldSet;
import org.springframework.validation.BindException;

public class TutorialFieldSetMapper implements FieldSetMapper<Tutorial> {

   @Override
   public Tutorial mapFieldSet(FieldSet fieldSet) throws BindException {
      // instantiating the Tutorial class
      Tutorial tutorial = new Tutorial();

      // Setting the fields from XML
      tutorial.setTutorial_id(fieldSet.readInt(0));
      tutorial.setTutorial_title(fieldSet.readString(1));
      tutorial.setTutorial_author(fieldSet.readString(2));
      tutorial.setTutorial_icon(fieldSet.readString(3));
      tutorial.setTutorial_description(fieldSet.readString(4));
      return tutorial;
   }
}

Tutorial.java

以下是 Tutorial 类。它是一个具有 settergetter 方法的简单类。

public class Tutorial {
   private int tutorial_id;
   private String tutorial_author;
   private String tutorial_title;
   private String submission_date;
   private String tutorial_icon;
   private String tutorial_description;

   @Override
   public String toString() {
      return " [id=" + tutorial_id + ", author=" + tutorial_author
         + ", title=" + tutorial_title + ", date=" + submission_date + ", icon ="
         +tutorial_icon +", description = "+tutorial_description+"]";
   }

   public int getTutorial_id() {
      return tutorial_id;
   }

   public void setTutorial_id(int tutorial_id) {
      this.tutorial_id = tutorial_id;
   }

   public String getTutorial_author() {
      return tutorial_author;
   }

   public void setTutorial_author(String tutorial_author) {
      this.tutorial_author = tutorial_author;
   }

   public String getTutorial_title() {
      return tutorial_title;
   }

   public void setTutorial_title(String tutorial_title) {
      this.tutorial_title = tutorial_title;
   }

   public String getSubmission_date() {
      return submission_date;
   }

   public void setSubmission_date(String submission_date) {
      this.submission_date = submission_date;
   }

   public String getTutorial_icon() {
      return tutorial_icon;
   }

   public void setTutorial_icon(String tutorial_icon) {
      this.tutorial_icon = tutorial_icon;
   }

   public String getTutorial_description() {
      return tutorial_description;
   }

   public void setTutorial_description(String tutorial_description) {
      this.tutorial_description = tutorial_description;
   }
}

App.java

以下是启动批处理的代码。在该类中,我们将通过运行 JobLauncher 来启动 Batch 应用程序。

public class App {
   public static void main(String[] args) throws Exception {
      String[] springConfig  = {    "jobs/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());
   }
}

执行此应用程序后,它将生成以下输出。

May 05, 2017 4:39:22 PM org.springframework.context.support.ClassPathXmlApplicationContext
prepareRefresh
INFO: Refreshing org.springframework.context.support.ClassPathXmlApplicationContext@306a30c7:
startup date [Fri May 05 16:39:22 IST 2017]; root of context hierarchy
May 05, 2017 4:39:23 PM org.springframework.beans.factory.xml.XmlBeanDefinitionReader loadBeanDefinitions
May 05, 2017 4:39:32 PM org.springframework.batch.core.job.SimpleStepHandler handleStep
INFO: Executing step: [step1]
Processing... [id=1001, author=Sanjay, title=Learn Java, date=06-05-2007,
icon =https://www.tutorialspoint.com/java/images/java-mini-logo.jpg,
description = Java is a high-level programming language originally developed by Sun Microsystems
and released in 1995. Java runs on a variety of platforms.
This tutorial gives a complete understanding of Java.');]
Hello
Processing.. [id=1002, author=Abdul S, title=Learn MySQL, date=19-04-2007,
icon =https://www.tutorialspoint.com/mysql/images/mysql-mini-logo.jpg,
description = MySQL is the most popular Open Source Relational SQL database management system.
MySQL is one of the best RDBMS being used for developing web-based software applications.
This tutorial will give you quick start with MySQL and make you comfortable with MySQL programming.]
Hello
Processing... [id=1003, author=Krishna Kasyap, title=Learn JavaFX, date=06-072017,
icon =https://www.tutorialspoint.com/javafx/images/javafx-mini-logo.jpg,
description = JavaFX is a Java library used to build Rich Internet Applications.
The applications developed using JavaFX can run on various devices
such as Desktop Computers, Mobile Phones, TVs, Tablets, etc.
This tutorial, discusses all the necessary elements of JavaFX
that are required to develop effective Rich Internet Applications]
Hello
May 05, 2017 4:39:36 PM org.springframework.batch.core.launch.support.SimpleJobLauncher run
INFO: Job: [FlowJob: [name=helloWorldJob]] completed with the following parameters: [{}]
and the following status: [COMPLETED]
Exit Status : COMPLETED

如果您在数据库中验证 details.tutorial 表,它将显示以下输出 −

tutorial _id

tutorial _author

tutorial _title

submission _date

tutorial _icon

tutorial _description

1001

Sanjay

Learn Java

06-05-2007

https://www.tutorials point.com /java/images/ java-mini-logo.jpg

Java 是一种高级编程语言,最初由 Sun Microsystems 开发并于 1995 年发布。Java 在各种平台上运行。本教程对 Java 给出了完整的理解。

1002

Abdul S

Learn MySQL

19-04-2007

https://www. tutorialspoint.com /mysql/images /mysql-minilogo.jpg

MySQL 是最流行的开源关系 SQL 数据库管理系统。MySQL 是用于开发基于 Web 的软件应用程序的最佳 RDBMS 之一。本教程将让您快速入门 MySQL,并让您对 MySQL 编程感到满意。

1003

Learn JavaFX

Krishna Kasyap

06-07-2017

https://www. tutorialspoint.com /javafx/images/ javafx-minilogo.jpg

MySQL 是最流行的开源关系 SQL 数据库管理系统。MySQL 是用于开发基于 Web 的软件应用程序的最佳 RDBMS 之一。本教程将让您快速入门 MySQL,并让您对 MySQL 编程感到满意。

这将生成一个 PDF,其中每一页都有记录,如下所示。

page thumbnails

Spring Batch - CSV to XML

在本章,我们将创建一个简单的 Spring Batch 应用程序,此应用程序使用 CSV Reader 和 XML Writer。

Reader − 我们在应用程序中使用的 readerFlatFileItemReader ,用于从 CSV 文件中读取数据。

以下是我们在此应用程序中使用的输入 CSV 文件。此文档保存指定详情记录的数据,例如教程 ID、教程作者、教程标题、提交日期、教程图标和教程描述。

1001, "Sanjay", "Learn Java", 06/05/2007
1002, "Abdul S", "Learn MySQL", 19/04/2007
1003, "Krishna Kasyap", "Learn JavaFX", 06/07/2017

Writer − 我们在应用程序中使用的 Writer 是 StaxEventItemWriter ,用于将数据写入 XML 文件。

Processor − 我们在应用程序中使用的 Processor 是一个自定义处理器,它只是打印从 CSV 文件中读取的记录。

jobConfig.xml

以下是我们样例 Spring Batch 应用程序的配置文件。在此文件中,我们将定义任务和步骤。此外,我们还定义 ItemReader、ItemProcessor 和 ItemWriter 的 bean。(在此,我们将其与各自的类相关联,并传递所需属性的值以对其进行配置。)

<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 = "../jobs/context.xml" />

   <bean id = "report" class = "Report" scope = "prototype" />
   <bean id = "itemProcessor" class = "CustomItemProcessor" />

   <batch:job id = "helloWorldJob">

      <batch:step id = "step1">

         <batch:tasklet>
            <batch:chunk reader = "cvsFileItemReader" writer = "xmlItemWriter"
               processor = "itemProcessor" commit-interval = "10">
            </batch:chunk>
         </batch:tasklet>
      </batch:step>
   </batch:job>

   <bean id = "cvsFileItemReader"
      class = "org.springframework.batch.item.file.FlatFileItemReader">
      <property name = "resource" value = "classpath:resources/report.csv" />
      <property name = "lineMapper">
         <bean
            class = "org.springframework.batch.item.file.mapping.DefaultLineMapper">
            <property name = "lineTokenizer">
               <bean
                  class = "org.springframework.batch.item.file.transform.DelimitedLineTokenizer">
                  <property name = "names" value = "tutorial_id,
                     tutorial_author, Tutorial_title, submission_date" />
               </bean>
            </property>

            <property name = "fieldSetMapper">
               <bean class = "ReportFieldSetMapper" />
            </property>
         </bean>
      </property>
   </bean>

   <bean id = "xmlItemWriter"
      class = "org.springframework.batch.item.xml.StaxEventItemWriter">
      <property name = "resource" value = "file:xml/outputs/tutorials.xml" />
      <property name = "marshaller" ref = "reportMarshaller" />
      <property name = "rootTagName" value = "tutorials" />
   </bean>

   <bean id = "reportMarshaller"
      class = "org.springframework.oxm.jaxb.Jaxb2Marshaller">
      <property name = "classesToBeBound">
         <list>
            <value>Tutorial</value>
         </list>
      </property>
   </bean>
</beans>

Context.xml

以下是我们 Spring Batch 应用程序的 context.xml 。在该文件中,我们将定义 Bean,如 Job 存储库、Job 启动器和事务管理器。

<beans xmlns = "http://www.springframework.org/schema/beans"
   xmlns:jdbc = "http://www.springframework.org/schema/jdbc"
   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
      http://www.springframework.org/schema/jdbc
      http://www.springframework.org/schema/jdbc/spring-jdbc-3.2.xsd">
   <!-- stored job-meta in database -->
   <bean id = "jobRepository"
      class = "org.springframework.batch.core.repository.support.JobRepositoryFactoryBean">
      <property name = "dataSource" ref = "dataSource" />
      <property name = "transactionManager" ref = "transactionManager" />
      <property name = "databaseType" value = "mysql" />
   </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>

   <bean id = "dataSource" class = "org.springframework.jdbc.datasource.DriverManagerDataSource">
      <property name = "driverClassName" value = "com.mysql.jdbc.Driver" />
      <property name = "url" value = "jdbc:mysql://localhost:3306/details" />
      <property name = "username" value = "myuser" />
      <property name = "password" value = "password" />
   </bean>

   <!-- create job-meta tables automatically -->
   <jdbc:initialize-database data-source = "dataSource">
      <jdbc:script location = "org/springframework/batch/core/schema-drop-mysql.sql" />
      <jdbc:script location = "org/springframework/batch/core/schema-mysql.sql" />
   </jdbc:initialize-database>
</beans>

CustomItemProcessor.java

以下是 Processor 类。在该类中,我们编写应用程序的处理代码。此处,我们打印每个记录的内容。

import org.springframework.batch.item.ItemProcessor;

public class CustomItemProcessor implements ItemProcessor<Tutorial, Tutorial> {

   @Override
   public Tutorial process(Tutorial item) throws Exception {
      System.out.println("Processing..." + item);
      return item;
   }
}

TutorialFieldSetMapper.java

以下是 TutorialFieldSetMapper 类,此类将数据设置为 Tutorial 类。

import org.springframework.batch.item.file.mapping.FieldSetMapper;
import org.springframework.batch.item.file.transform.FieldSet;
import org.springframework.validation.BindException;

public class TutorialFieldSetMapper implements FieldSetMapper<Tutorial> {

   @Override
   public Tutorial mapFieldSet(FieldSet fieldSet) throws BindException {

      //Instantiating the report object
      Tutorial tutorial = new Tutorial();

      //Setting the fields
      tutorial.setTutorial_id(fieldSet.readInt(0));
      tutorial.setTutorial_author(fieldSet.readString(1));
      tutorial.setTutorial_title(fieldSet.readString(2));
      tutorial.setSubmission_date(fieldSet.readString(3));

      return tutorial;
   }
}

Tutorial.java class

以下是 Tutorial 类。它是一个简单的 Java 类,具有 settergetter 方法。在该类中,我们使用注解来将该类的这些方法与 XML 文件的这些标记相关联。

import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;

@XmlRootElement(name = "tutorial")
public class Tutorial {
   private int tutorial_id;
   private String tutorial_author;
   private String tutorial_title;
   private String submission_date;

   @XmlAttribute(name = "tutorial_id")
   public int getTutorial_id() {
      return tutorial_id;
   }

   public void setTutorial_id(int tutorial_id) {
      this.tutorial_id = tutorial_id;
   }

   @XmlElement(name = "tutorial_author")
   public String getTutorial_author() {
      return tutorial_author;
   }
   public void setTutorial_author(String tutorial_author) {
      this.tutorial_author = tutorial_author;
   }

   @XmlElement(name = "tutorial_title")
   public String getTutorial_title() {
      return tutorial_title;
   }

   public void setTutorial_title(String tutorial_title) {
      this.tutorial_title = tutorial_title;
   }

   @XmlElement(name = "submission_date")
   public String getSubmission_date() {
      return submission_date;
   }

   public void setSubmission_date(String submission_date) {
      this.submission_date = submission_date;
   }

   @Override
   public String toString() {
      return "  [Tutorial id=" + tutorial_id + ",
         Tutorial Author=" + tutorial_author  + ",
         Tutorial Title=" + tutorial_title + ",
         Submission Date=" + submission_date + "]";
   }
}

App.java

以下是启动批处理的代码。在此类中,我们将通过运行 JobLauncher 来启动批处理应用程序。

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 {

      String[] springConfig  =  { "jobs/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());
   }
}

执行此应用程序后,它将生成以下输出。

May 08, 2017 10:10:12 AM org.springframework.context.support.ClassPathXmlApplicationContext prepareRefresh
INFO: Refreshing
org.springframework.context.support.ClassPathXmlApplicationContext@3d646c37: startup date
[Mon May 08 10:10:12 IST 2017]; root of context hierarchy
May 08, 2017 10:10:12 AM org.springframework.beans.factory.xml.XmlBeanDefinitionReader loadBeanDefinitions
May 08, 2017 10:10:15 AM org.springframework.jdbc.datasource.init.ScriptUtils executeSqlScript
INFO: Executing step: [step1]
Processing...  [Tutorial id=1001, Tutorial Author=Sanjay,
Tutorial Title=Learn Java, Submission Date=06/05/2007]
Processing...  [Tutorial id=1002, Tutorial Author=Abdul S,
Tutorial Title=Learn MySQL, Submission Date=19/04/2007]
Processing...  [Tutorial id=1003, Tutorial Author=Krishna Kasyap,
Tutorial Title=Learn JavaFX, Submission Date=06/07/2017]
May 08, 2017 10:10:21 AM org.springframework.batch.core.launch.support.SimpleJobLauncher run
INFO: Job: [FlowJob: [name=helloWorldJob]] completed with the following parameters:
[{}] and the following status: [COMPLETED]
Exit Status : COMPLETED

这将生成包含以下内容的 XML 文件。

<?xml version = "1.0" encoding = "UTF-8"?>
<tutorials>
   <tutorial tutorial_id = "1001">
      <submission_date>06/05/2007</submission_date>
      <tutorial_author>Sanjay</tutorial_author>
      <tutorial_title>Learn Java</tutorial_title>
   </tutorial>

   <tutorial tutorial_id = "1002">
      <submission_date>19/04/2007</submission_date>
      <tutorial_author>Abdul S</tutorial_author>
      <tutorial_title>Learn MySQL</tutorial_title>
   </tutorial>

   <tutorial tutorial_id = "1003">
      <submission_date>06/07/2017</submission_date>
      <tutorial_author>Krishna Kasyap</tutorial_author>
      <tutorial_title>Learn JavaFX</tutorial_title>
   </tutorial>
</tutorials>

Spring Batch - MySQL to XML

在本章中,我们将创建一个 Spring Batch 应用程序,它使用 MySQL reader 和 XML Writer。

Reader − 应用程序中使用的 reader 是 JdbcCursorItemReader ,用来从 MySQL 数据库中读取数据。

假设我们在 MySQL 数据库中创建了一个表,如下所示 −

CREATE TABLE details.xml_mysql(
   person_id int(10) NOT NULL,
   sales VARCHAR(20),
   qty int(3),
   staffName VARCHAR(20),
   date VARCHAR(20)
);

假设我们在其中插入了以下记录。

mysql> select * from tutorialsdata;
+-------------+-----------------+----------------+-----------------+
| tutorial_id | tutorial_author | tutorial_title | submission_date |
+-------------+-----------------+----------------+-----------------+
|         101 | Sanjay          | Learn Java     | 06-05-2007      |
|         102 | Abdul S         | Learn MySQL    | 19-04-2007      |
|         103 | Krishna Kasyap  | Learn JavaFX   | 06-07-2017      |
+-------------+-----------------+----------------+-----------------+
3 rows in set (0.00 sec)

Writer − 应用程序中使用的 Writer 是 StaxEventItemWriter ,用来将数据写入 XML 文件。

Processor − 我们在应用程序中使用的 Processor 是一个自定义处理器,它只是打印从 CSV 文件中读取的记录。

jobConfig.xml

以下是样例 Spring Batch 应用程序的配置文件。在该文件中,我们将定义 Job 和 Step。此外,我们还定义了 ItemReader、ItemProcessor 和 ItemWriter 的 bean。(在这里,我们将它们与其各自的类合并,并传递所需的属性值来配置它们。)

<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"
   xmlns:util = "http://www.springframework.org/schema/util"
   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 = "../jobs/context.xml" />

   <bean id = "report" class = "Report" scope = "prototype" />
   <bean id = "itemProcessor" class = "CustomItemProcessor" />

   <batch:job id = "helloWorldJob">
      <batch:step id = "step1">
         <batch:tasklet>
            <batch:chunk reader = "dbItemReader"
               writer = "mysqlItemWriter" processor = "itemProcessor" commit-interval = "10">
            </batch:chunk>
         </batch:tasklet>
      </batch:step>
   </batch:job>

   <bean id = "dbItemReader"
      class = "org.springframework.batch.item.database.JdbcCursorItemReader" scope = "step">
      <property name = "dataSource" ref = "dataSource" />
      <property name = "sql" value = "select * from tutorials_data" />
      <property name = "rowMapper">
         <bean class = "TutorialRowMapper" />
      </property>
   </bean>
   <bean id = "mysqlItemWriter"
      class = "org.springframework.batch.item.xml.StaxEventItemWriter">
      <property name = "resource" value = "file:xml/outputs/tutorials.xml" />
      <property name = "marshaller" ref = "reportMarshaller" />
      <property name = "rootTagName" value = "Tutorial" />
   </bean>

   <bean id = "reportMarshaller" class = "org.springframework.oxm.jaxb.Jaxb2Marshaller">
      <property name = "classesToBeBound">
         <list>
            <value>Tutorial</value>
         </list>
      </property>
   </bean>
</beans>

Context.xml

以下是我们 Spring Batch 应用程序的 context.xml 。在该文件中,我们将定义 Bean,如 Job 存储库、Job 启动器和事务管理器。

<beans xmlns = " http://www.springframework.org/schema/beans"
   xmlns:jdbc = "http://www.springframework.org/schema/jdbc"
   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
      http://www.springframework.org/schema/jdbc
      http://www.springframework.org/schema/jdbc/spring-jdbc-3.2.xsd ">

   <!-- stored job-meta in database -->
   <bean id = "jobRepository"
      class = "org.springframework.batch.core.repository.support.JobRepositoryFactoryBean">
      <property name = "dataSource" ref = "dataSource" />
      <property name = "transactionManager" ref = "transactionManager" />
      <property name = "databaseType" value = "mysql" />
   </bean>

   <bean id = "transactionManager"
      class = "org.springframework.batch.support.transaction.ResourcelessTransactionMana ger" />
   <bean id = "jobLauncher"
      class = "org.springframework.batch.core.launch.support.SimpleJobLauncher">
      <property name = "jobRepository" ref = "jobRepository" />
   </bean>

   <!-- connect to MySQL database -->
   <bean id = "dataSource"
      class = "org.springframework.jdbc.datasource.DriverManagerDataSource">
      <property name = "driverClassName" value = "com.mysql.jdbc.Driver" />
      <property name = "url" value = "jdbc:mysql://localhost:3306/details" />
      <property name = "username" value = "myuser" />
      <property name = "password" value = "password" />
   </bean>

   <!-- create job-meta tables automatically -->
   <jdbc:initialize-database data-source = "dataSource">
      <jdbc:script location = "org/springframework/batch/core/schema-drop-mysql.sql" />
      <jdbc:script location = "org/springframework/batch/core/schema-mysql.sql" />
   </jdbc:initialize-database>
</beans>

CustomItemProcessor.java

以下是 Processor 类。在该类中,我们编写应用程序的处理代码。此处,我们打印每个记录的内容。

import org.springframework.batch.item.ItemProcessor;

public class CustomItemProcessor implements ItemProcessor<Tutorial, Tutorial> {

   @Override
   public Tutorial process(Tutorial item) throws Exception {
      System.out.println("Processing..." + item);
      return item;
   }
}

TutorialRowMapper.java

以下是 TutorialRowMapper 类,它将数据设置为 Tutorial 类。

import java.sql.ResultSet;
import java.sql.SQLException;
import org.springframework.jdbc.core.RowMapper;

public class TutorialRowMapper implements RowMapper<Tutorial> {

   @Override
   public Tutorial mapRow(ResultSet rs, int rowNum) throws SQLException {

      Tutorial tutorial = new Tutorial();
      tutorial.setTutorial_id(rs.getInt("tutorial_id"));
      tutorial.setTutorial_author(rs.getString("tutorial_author"));
      tutorial.setTutorial_title(rs.getString("tutorial_title"));
      tutorial.setSubmission_date(rs.getString("submission_date"));
      return tutorial;
   }
}

Tutorial.java

以下是 Tutorial 类。它是一个简单的 Java 类,具有 settergetter 方法。在该类中,我们使用注解来将该类的这些方法与 XML 文件的这些标记相关联。

import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;

@XmlRootElement(name = "details")
public class Tutorial {

   int tutorial_id;
   String tutorial_author;
   String submission_date;

   @XmlAttribute(name = "tutorial_id")
   public int getTutorial_id() {
      return tutorial_id;
   }

   public void setTutorial_id(int tutorial_id) {
      this.tutorial_id = tutorial_id;
   }

   @XmlElement(name = "tutorial_author")
   public String getTutorial_author() {
      return tutorial_author;
   }

   public void setTutorial_author(String tutorial_author) {
      this.tutorial_author = tutorial_author;
   }

   @XmlElement(name = "tutorial_title")
   public String getTutorial_title() {
      return tutorial_title;
   }

   public void setTutorial_title(String tutorial_title) {
      this.tutorial_title = tutorial_title;
   }

   @XmlElement(name = "submission_date")
   public String getSubmission_date() {
      return submission_date;
   }

   public void setSubmission_date(String submission_date) {
      this.submission_date = submission_date;
   }

   public String toString() {
      return " [Tutorial Id=" + tutorial_id + ",
      Tutorial Author =" + tutorial_author  + ",
      Tutorial Title =" + tutorial_title + ",
      Submission Date =" + submission_date + "]";
   }
}

App.java

以下是启动批处理的代码。在该类中,我们将通过运行 JobLauncher 来启动 Batch 应用程序。

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 {

      String[] springConfig  =  { "jobs/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());
   }
}

执行此应用程序后,它将生成以下输出。

May 08, 2017 11:32:06 AM org.springframework.context.support.ClassPathXmlApplicationContext prepareRefresh
INFO: Refreshing org.springframework.context.support.ClassPathXmlApplicationContext@3d646c37:
startup date [Mon May 08 11:32:06 IST 2017]; root of context hierarchy
May 08, 2017 11:32:06 AM org.springframework.beans.factory.xml.XmlBeanDefinitionReader loadBeanDefinitions
INFO: Loading XML bean definitions from class path resource [jobs/job_hello_world.xml]
May 08, 2017 11:32:07 AM org.springframework.beans.factory.xml.XmlBeanDefinitionReader loadBeanDefinitions
May 08, 2017 11:32:14 AM org.springframework.batch.core.job.SimpleStepHandler handleStep
INFO: Executing step: [step1]
Processing... [Tutorial Id=101, Tutorial Author=Sanjay,
Tutorial Title=Learn Java, Submission Date=06-05-2007]
Processing... [Tutorial Id=102, Tutorial Author=Abdul S,
Tutorial Title=Learn MySQL, Submission Date=19-04-2007]
Processing... [Tutorial Id=103, Tutorial Author=Krishna Kasyap,
Tutorial Title=Learn JavaFX, Submission Date=06-07-2017]
May 08, 2017 11:32:14 AM org.springframework.batch.core.launch.support.SimpleJobLauncher run
INFO: Job: [FlowJob: [name=helloWorldJob]] completed with the following parameters:
[{}] and the following status: [COMPLETED]
Exit Status : COMPLETED

这将生成包含以下内容的 XML 文件。

<?xml version = "1.0" encoding = "UTF-8"?>
<Tutorial>
   <details tutorial_id = "101">
      <submission_date>06-05-2007</submission_date>
      <tutorial_author>Sanjay</tutorial_author>
      <tutorial_title>Learn Java</tutorial_title>
   </details>

   <details tutorial_id = "102">
      <submission_date>19-04-2007</submission_date>
      <tutorial_author>Abdul S</tutorial_author>
      <tutorial_title>Learn MySQL</tutorial_title>
   </details>

   <details tutorial_id = "103">
      <submission_date>06-07-2017</submission_date>
      <tutorial_author>Krishna Kasyap</tutorial_author>
      <tutorial_title>Learn JavaFX</tutorial_title>
   </details>
</Tutorial>

Spring Batch - MySQL to Flat File

在本章中,我们将创建一个 Spring Batch 应用程序,该应用程序使用 MySQL Reader 和 Flatfile Writer(.txt)。

Reader − 我们在应用程序中使用的 Reader 是 JdbcCursorItemReader ,用于从 MySQL 数据库中读取数据。

假设我们在 MySQL 数据库中创建了一个表格,如下所示。

CREATE TABLE details.xml_mysql(
   person_id int(10) NOT NULL,
   sales VARCHAR(20),
   qty int(3),
   staffName VARCHAR(20),
   date VARCHAR(20)
);

假设我们已向其中插入了以下记录。

mysql> select * from tutorialsdata;
+-------------+-----------------+----------------+-----------------+
| tutorial_id | tutorial_author | tutorial_title | submission_date |
+-------------+-----------------+----------------+-----------------+
|         101 | Sanjay          | Learn Java     | 06-05-2007      |
|         102 | Abdul S         | Learn MySQL    | 19-04-2007      |
|         103 | Krishna Kasyap  | Learn JavaFX   | 06-07-2017      |
+-------------+-----------------+----------------+-----------------+
3 rows in set (0.00 sec)

Writer − 我们在应用程序中使用的 Writer 是 FlatFileItemWriter ,用于将数据写入 flatfile (.txt)。

Processor − 我们在应用程序中使用的 Processor 是一个自定义处理器,它只是打印从 CSV 文件中读取的记录。

jobConfig.xml

以下是我们示例 Spring Batch 应用程序的配置文件。在该文件中,我们将定义 Job 和 Steps。除这些之外,我们还定义 ItemReader、ItemProcessor 和 ItemWriter 的 Bean。(在此处,我们将它们与各自的类相关联,并传递必需属性的值来配置它们。)

<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"
   xmlns:util = "http://www.springframework.org/schema/util"
   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 = "../jobs/context.xml" />
   <bean id = "tutorial" class = "Tutorial" scope = "prototype" />
   <bean id = "itemProcessor" class = "CustomItemProcessor" />

   <batch:job id = "helloWorldJob">
      <batch:step id = "step1">
         <batch:tasklet>
            <batch:chunk reader = "mysqlItemReader"
               writer = "flatFileItemWriter" processor = "itemProcessor"
               commit-interval = "10">
            </batch:chunk>
         </batch:tasklet>
      </batch:step>
   </batch:job>

   <bean id = "mysqlItemReader"
      class = "org.springframework.batch.item.database.JdbcCursorItemReader" >
      <property name = "dataSource" ref = "dataSource" />
      <property name = "sql" value = "select * from details.tutorialsdata" />
      <property name = "rowMapper">
         <bean class = "TutorialRowMapper" />
      </property>
   </bean>

   <bean id = "flatFileItemWriter"
      class = " org.springframework.batch.item.file.FlatFileItemWriter">
      <property name = "resource" value = "file:target/outputfiles/employee_output.txt"/>
      <property name = "lineAggregator">
         <bean class = " org.springframework.batch.item.file.transform.PassThroughLineAggregator"/>
      </property>
   </bean>
</beans>

Context.xml

以下是我们 Spring Batch 应用程序的 context.xml 。在该文件中,我们将定义 Bean,如 Job 存储库、Job 启动器和事务管理器。

<beans xmlns = "http://www.springframework.org/schema/beans"
   xmlns:xsi = "http://www.w3.org/2001/XMLSchema-instance"
   xmlns:jdbc = "http://www.springframework.org/schema/jdbc"
   xsi:schemaLocation = "http://www.springframework.org/schema/beans
      http://www.springframework.org/schema/beans/spring-beans-3.2.xsd
      http://www.springframework.org/schema/jdbc
      http://www.springframework.org/schema/jdbc/spring-jdbc-3.2.xsd ">

   <!-- stored job-meta in database -->
   <bean id = "jobRepository"
      class = "org.springframework.batch.core.repository.support.JobRepositoryFactoryBean">
      <property name = "dataSource" ref = "dataSource" />
      <property name = "transactionManager" ref = "transactionManager" />
      <property name = "databaseType" value = "mysql" />
   </bean>

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

   <bean id = "dataSource"
      class = "org.springframework.jdbc.datasource.DriverManagerDataSource">
      <property name = "driverClassName" value = "com.mysql.jdbc.Driver" />
      <property name = "url" value = "jdbc:mysql://localhost:3306/details" />
      <property name = "username" value = "myuser" />
      <property name = "password" value = "password" />
   </bean>

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

   <!-- create job-meta tables automatically -->
   <jdbc:initialize-database data-source = "dataSource">
      <jdbc:script location = "org/springframework/batch/core/schema-drop-mysql.sql" />
      <jdbc:script location = "org/springframework/batch/core/schema-mysql.sql" />
   </jdbc:initialize-database>
</beans>

CustomItemProcessor.java

以下是 Processor 类。在该类中,我们编写应用程序的处理代码。此处,我们打印每个记录的内容。

import org.springframework.batch.item.ItemProcessor;

// Implementing the ItemProcessor interface
public class CustomItemProcessor implements ItemProcessor<Tutorial, Tutorial> {

   @Override
   public Tutorial process(Tutorial item) throws Exception {
      System.out.println("Processing..." + item);
      return item;
   }
}

TutorialRowMapper.java

以下是 TutorialRowMapper 类,它将数据设置为 Tutorial 类。

public class TutorialRowMapper implements RowMapper<Tutorial> {

   @Override
   public Tutorial mapRow(ResultSet rs, int rowNum) throws SQLException {

      Tutorial tutorial = new Tutorial();

      tutorial.setTutorial_id(rs.getInt("tutorial_id"));
      tutorial.setTutorial_title(rs.getString("tutorial_title"));
      tutorial.setTutorial_author(rs.getString("tutorial_author"));
      tutorial.setSubmission_date(rs.getString("submission_date"));
      return tutorial;
   }
}

Tutorial.java

以下是 Tutorial 类。它是一个简单的 Java 类,具有 settergetter 方法。在该类中,我们使用注解来将该类的这些方法与 XML 文件的这些标记相关联。

public class Tutorial {
   private int tutorial_id;
   private String tutorial_title;
   private String tutorial_author;
   private String submission_date;

   public int getTutorial_id() {
      return tutorial_id;
   }

   public void setTutorial_id(int tutorial_id) {
      this.tutorial_id = tutorial_id;
   }

   public String getTutorial_title() {
      return tutorial_title;
   }

   public void setTutorial_title(String tutorial_title) {
      this.tutorial_title = tutorial_title;
   }

   public String getTutorial_author() {
      return tutorial_author;
   }

   public void setTutorial_author(String tutorial_author) {
      this.tutorial_author = tutorial_author;
   }

   public String getSubmission_date() {
      return submission_date;
   }
   public void setSubmission_date(String submission_date) {
      this.submission_date = submission_date;
   }

   @Override
   public String toString() {
      return " [id=" + tutorial_id + ", title=" +
      tutorial_title                      + ",
      author=" + tutorial_author + ", date=" +
      submission_date + "]";
   }
}

App.java

以下是启动批处理的代码。在该类中,我们将通过运行 JobLauncher 来启动 Batch 应用程序。

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 {

      String[] springConfig  =  { "jobs/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());
   }
}

执行此应用程序后,它将生成以下输出。

May 09, 2017 5:44:48 PM org.springframework.context.support.ClassPathXmlApplicationContext prepareRefresh
INFO: Refreshing org.springframework.context.support.ClassPathXml
ApplicationContext@3d646c37: startup date [Tue May
09 17:44:48 IST 2017]; root of context hierarchy
May 09, 2017 5:44:48 PM org.springframework.beans.factory.xml.XmlBeanDefinitionReader loadBeanDefinitions
May 09, 2017 5:44:56 PM org.springframework.batch.core.launch.support.SimpleJobLauncher run
INFO: Job: [FlowJob: [name=helloWorldJob]] launched
with the following parameters: [{}]
May 09, 2017 5:44:56 PM org.springframework.batch.core.job.SimpleStepHandler handleStep
INFO: Executing step: [step1]
Processing...Report [id=101, title=Learn Java, author=Sanjay, date=06-05-2007]
Processing...Report [id=102, title=Learn MySQL, author=Abdul S, date=19-04-2007]
Processing...Report [id=103, title=Learn JavaFX, author=Krishna Kasyap, date=0607-2017]
May 09, 2017 5:44:57 PM org.springframework.batch.core.launch.support.SimpleJobLauncher run
INFO: Job: [FlowJob: [name=helloWorldJob]] completed with the following parameters:
[{}] and the following status: [COMPLETED]
Hello
Exit Status : COMPLETED

这将生成一个内容如下所示的 .txt 文件。

Report [id=101, title=Learn Java, author=Sanjay, date=06-05-2007]
Report [id=102, title=Learn MySQL, author=Abdul S, date=19-04-2007]
Report [id=103, title=Learn JavaFX, author=Krishna Kasyap, date=06-07-2017]