目录

Spring Batch - 快速指南

Spring Batch - Overview

Batch processing是一种处理模式,涉及执行一系列自动复杂作业而无需用户交互。 批处理过程处理批量数据并长时间运行。

一些企业应用程序需要处理大量数据以执行涉及的操作 -

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

  • 在大型数据集上重复处理的定期应用程序。

  • 处理以事务方式处理和验证数据的应用程序。

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

什么是Spring Batch

Spring批处理是一个lightweight framework ,用于开发企业应用程序中使用的Batch Applications程序。

除批量处理外,该框架还提供以下功能:

  • 包括日志记录和跟踪
  • 交易管理
  • Job processing statistics
  • Job restart
  • 跳过和资源管理

您还可以使用其分割技术来缩放弹簧批量应用程序。

Spring Batch的特点

以下是Spring Batch的显着特征 -

  • Flexibility - Spring Batch应用程序非常灵活。 您只需更改XML文件即可更改应用程序中的处理顺序。

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

  • Scalability - 使用分割技术,您可以扩展Spring Batch应用程序。 这些技巧可以让你 -

    • 并行执行作业的步骤。

    • 并行执行单个线程。

  • Reliability - 如果发生任何故障,您可以通过解除步骤来从正好停止的位置重新启动作业。

  • Support for multiple file formats - Spring Batch支持大量读取器和编写器,如XML,平面文件,CSV,MYSQL,Hibernate,JDBC,Mongo,Neo4j等。

  • Multiple ways to launch a job - 您可以使用Web应用程序,Java程序,命令行等启动Spring Batch作业。

除此之外,Spring Batch应用程序支持 -

  • 失败后自动重试。

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

  • 运行并发作业。

  • 日志记录,资源管理,跳过和重新启动处理等服务。

Spring Batch - Environment

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

有关Eclipse的更多信息,请参阅我们的Eclipse教程。

在Eclipse上设置Spring Batch

按照下面给出的步骤在Eclipse上设置Spring Batch环境。

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

新项目

Step 2 - 创建一个Sample Spring Batch项目,如下所示。

项目名

Step 3 - 右键单击​​项目并将其转换为Maven项目,如下所示。 一旦将其转换为Maven项目,它将为您提供一个Pom.xml ,您需要在其中提及所需的依赖项。 此后,这些jar文件将自动下载到您的项目中。

配置

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

最后,如果您观察Maven依赖项,您可以观察到已下载了所有必需的jar文件。

Jar文件

Spring Batch - Architecture

以下是Spring Batch架构的图解表示。 如图所示,该体系结构包含三个主要组件,即Application, Batch CoreBatch Infrastructure

建筑

Application - 该组件包含我们使用Spring Batch框架编写的所有作业和代码。

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

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

Spring Batch的组件

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

组件

工作

在Spring Batch应用程序中,作业是要执行的批处理。 它从头到尾不间断地运行。 此作业进一步分为步骤(或作业包含步骤)。

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

<job id = "jobid"> 
   <step id = "step1" next = "step2"/> 
   <step id = "step2" next = "step3"/> 
   <step id = "step3"/> 
</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

读者,作家和处理者

item reader从特定源将数据读入Spring Batch应用程序,而item writer编写器将数据从Spring Batch应用程序写入特定目标。

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

当没有给出读写器时, tasklet充当SpringBatch的处理器。 它只处理一个任务。 例如,如果我们正在编写一个简单的步骤,我们从MySQL数据库读取数据并处理它并将其写入文件(平面),那么我们的步骤使用 -

  • 从MySQL数据库读取的读取reader

  • 写入平面文件的编写器。

  • 一个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

JobIinstance表示作业的逻辑运行; 它是在我们开始工作时创建的。 每个作业实例由作业名称和运行时传递给它的参数区分。

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

JobExecution和StepExecution

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

Spring Batch - Application

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

  • 配置文件(XML文件)
  • Tasklet /处理器(Java类)
  • 带有setter和getter的Java类(Java类(bean))
  • Mapper类(Java类)
  • 启动类(Java类)

配置文件

配置文件(XML)包含以下内容 -

  • jobstep定义。

  • 豆类定义readerswriters

  • JobLauncher,JobRepository,Transaction Manager和Data Source等组件的定义。

在我们的示例中,为了更好地理解,我们将其分为两个文件: job.xml文件(定义job,step,reader和writer)和context.xml文件(作业启动器,作业存储库,事务管理器和数据源)。

映射器类

Mapper类(取决于读者)实现了诸如row mapperfield set mapper等接口。它包含从读取器获取数据并使用settergetter方法将其设置为Java类的代码(Java Bean) 。

Java Bean类

具有settersgetters (Java bean)的Java类表示具有多个值的数据。 它充当助手类。 我们将以一个对象的形式将数据从一个组件(读取器,编写器,处理器)传递给其他组件。

Tasklet/processor

Tasklet/processor类包含Spring Batch应用程序的处理代码。 处理器是一个类,它接受包含读取数据的对象,处理它,并返回处理过的数据(在表单对象中)。

启动器类

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

应用

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 属性和描述
1

Id

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

2

restartable

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

以下是SpringBatch作业的XML配置。

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

Step

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

S.No 属性和描述
1

Id

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

2

next

这是指定下一步的快捷方式。

3

parent

它用于指定配置应从中继承的父bean的名称。

以下是SpringBatch步骤的XML配置。

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

Chunk

此标记用于定义/配置tasklet一个块。 它具有以下四个属性 -

S.No 属性和描述
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 属性和描述
1

dataSource

它用于指定定义数据源的bean名称。

2

transactionManager

它用于指定定义transactionmanager的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

数据源bean用于配置Datasource 。 此bean与org.springframework.jdbc.datasource.DriverManagerDataSource类型的类相关联。

S.No 属性和描述
1

driverClassName

它指定用于连接数据库的驱动程序的类名。

2

url

这指定了数据库的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批处理应用程序,而Item Writer将数据从Spring Batch应用程序写入特定目标。

Item processor是一个包含处理代码的类,该处理代码处理读入弹簧批处理的数据。 如果应用程序读取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,flatfile,CSV等。

要在您的应用程序中包含一个阅读器,您需要为该阅读器定义一个bean,为bean中的所有必需属性提供值,并将此类bean的id作为值传递给chunk元素reader的属性(同样为writer )。

ItemReader

它是读取数据的步骤(批处理过程)的实体。 ItemReader一次读取一个项目。 Spring Batch提供了一个Interface ItemReader 。 所有readers实现了这个界面。

以下是Spring Batch提供的一些预定义的ItemReader类,可以从各种来源中读取。

读者 目的
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提供了一个Interface ItemWriter 。 所有作者都实现了这个接口。

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

作家 目的
FlatFIleItemWriter 将数据写入平面文件。
StaxEventItemWriter 将数据写入XML文件。
StoredProcedureItemWriter 将数据写入数据库的存储过程。
JDBCPagingItemWriter 将数据写入关系数据库数据库。
MongoItemWriter 将数据写入MongoDB。
Neo4jItemWriter 将数据写入Neo4j。

同样,我们需要通过创建bean来配置ItemWriters。 以下是JdbcCursorItemReader的示例, JdbcCursorItemReader数据写入MySQL数据库。

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

物品处理器

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应用程序包含以下文件 -

  • Configuration file - 这是一个XML文件,我们在其中定义作业和作业的步骤。 (如果应用程序也涉及读者和编写者,那么读者和编写者的配置也包含在此文件中。)

  • Context.xml - 在此文件中,我们将定义诸如作业存储库,作业启动程序和事务管理器之类的bean。

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

  • Launcher class - 在此类中,我们将通过运行Job启动器来启动Batch Application。

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 Reader和MySQL Writer的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.iowiki.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.iowiki.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.iowiki.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 - 我们在应用程序中使用的编写器是JdbcBatchItemWriter用于将数据写入MySQL数据库。 假设我们在MySQL中创建了一个名为"details"的数据库中的表。

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"记录或数据元素,那么对于每个记录,它将读取数据,处理它,并在Writer中写入数据。 为了处理数据,它在传递的处理器上进行中继。 在这种情况下,在自定义处理器类中,我们编写了代码来加载特定的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。

<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

以下是ReportFieldSetMapper类,它将数据设置为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 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启动批处理应用程序。

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] 
<b class="notranslate">Processing</b>... [id=1001, author=Sanjay, title=Learn Java, date=06-05-2007, 
icon =https://www.iowiki.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 
<b class="notranslate">Processing</b>.. [id=1002, author=Abdul S, title=Learn MySQL, date=19-04-2007, 
icon =https://www.iowiki.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 
<b class="notranslate">Processing</b>... [id=1003, author=Krishna Kasyap, title=Learn JavaFX, date=06-072017, 
icon =https://www.iowiki.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表,它将显示以下输出 -

教程_id tutorial _author 教程_title 提交日期 教程_icon 教程_description
1001Sanjay 学习Java 06-05-2007 https://www.tutorials point.com/java/images/java-mini-logo.jpg Java是一种高级编程语言,最初由Sun Microsystems开发并于1995年发布.Java可在各种平台上运行。 本教程提供了对Java的完整理解。
1002Abdul S 学习MySQL 19-04-2007 https://开头WWW。 iowiki.com/mysql/images /mysql-minilogo.jpg MySQL是最流行的开源关系SQL数据库管理系统。 MySQL是用于开发基于Web的软件应用程序的最佳RDBMS之一。 本教程将为您提供MySQL的快速入门,让您熟悉MySQL编程。
1003 学习JavaFX Krishna Kasyap06-07-2017 https://开头WWW。 iowiki.com/javafx/images/javafx-minilogo.jpg MySQL是最流行的开源关系SQL数据库管理系统。 MySQL是用于开发基于Web的软件应用程序的最佳RDBMS之一。 本教程将为您提供MySQL的快速入门,让您熟悉MySQL编程。

这将生成一个PDF,其中包含每页上的记录,如下所示。

页面缩略图

Spring Batch - CSV to XML

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

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 - 我们在应用程序中使用的处理器是一个自定义处理器,它只打印从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。

<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类。 它是一个带有settergetter方法的简单Java类。 在这个类中,我们使用注释将此类的方法与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

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

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 - 我们在应用程序中使用的处理器是一个自定义处理器,它只打印从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" 
   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。

<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类。 它是一个带有settergetter方法的简单Java类。 在这个类中,我们使用注释将此类的方法与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启动批处理应用程序。

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

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

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 - 我们在应用程序中使用的处理器是一个自定义处理器,它只打印从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" 
   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。

<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类。 它是一个带有settergetter方法的简单Java类。 在这个类中,我们使用注释将此类的方法与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启动批处理应用程序。

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] 
<b class="notranslate">Processing</b>...Report [id=101, title=Learn Java, author=Sanjay, date=06-05-2007] 
<b class="notranslate">Processing</b>...Report [id=102, title=Learn MySQL, author=Abdul S, date=19-04-2007] 
<b class="notranslate">Processing</b>...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] 
↑回到顶部↑
WIKI教程 @2018