1 概述

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

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

  • 基于时间的事件,如周期性计算。
  • 在大型数据集上重复处理的定期应用程序。
  • 处理和验证交易方式中可用数据的应用程序。

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

什么是Spring批处理

Spring批处理是一个轻量级框架,用于开发在企业应用程序中使用的批处理应用程序。

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

  • 包括日志和跟踪
  • 交易管理
  • 作业处理统计
  • 作业重启
  • 跳过和资源管理

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

Spring Batch的特点

以下是Spring Batch的显着特点 -

  • 灵活性 - Spring批处理应用程序非常灵活。您只需更改XML文件即可更改应用程序中的处理顺序。
  • 可维护性 - Spring批量应用程序易于维护。Spring Batch作业包括步骤,每个步骤都可以进行分离,测试和更新,而不影响其他步骤。
  • 可伸缩性 - 使用分区技术,您可以缩放Spring Batch应用程序。这些技术可以让你 -
  • 并行执行作业的步骤。
  • 并行执行单个线程。
  • 可靠性 - 如果发生任何故障,您可以通过将步骤分离,从完全停止的地方重新开始工作。
  • 支持多种文件格式 - Spring Batch为XML,Flat文件,CSV,MYSQL,Hibernate,JDBC,Mongo,Neo4j等大量读者和作者提供支持。
  • 多种启动作业的方式 - 您可以使用Web应用程序,Java程序,命令行等来启动Spring Batch作业。

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

  • 失败后自动重试。
  • 跟踪批次执行过程中和完成批次处理后的状态和统计数据。
  • 运行并行作业。
  • 诸如日志记录,资源管理,跳过和重新启动处理等服务。

2 批处理架构

以下是Spring Batch体系结构的图示。如图所示,该体系结构包含三个主要组件,即应用程序,批核和批处理基础架构。


spring boot批量删除百万数据 spring批量处理_spring boot批量删除百万数据

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

批核 - 该组件包含控制和启动批作业所需的所有API类。

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

Spring 批处理的组件

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


spring boot批量删除百万数据 spring批量处理_spring boot批量删除百万数据_02

Job

在Spring Batch应用程序中,作业是要执行的批处理过程。它从头至尾无间断运行。这项工作进一步分为几个步骤(或一个工作包含步骤)。

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

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

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

可重新启动 - 通常,当作业正在运行时,我们尝试再次启动它,这被认为是重新启动,并且会重新启动。为避免这种情况,您需要将可重新启动的值设置为false,如下所示。

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

</job>

Step

甲步骤是其中包含必要的信息以定义并执行作业(其一部分)的作业的一个独立部分。

如图所示,每个步骤由ItemReader,ItemProcessor(可选)和ItemWriter组成。工作可能包含一个或多个步骤。

Readers,Writers,and Processors

一个项目读取器数据读入来自特定源的一个Spring批量应用,而一个项目写入器从Spring批处理应用到特定目的地写入数据。

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

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

  • 一个reader从MySQL数据库中读取。
  • 一位撰写平面文件的writer
  • 根据我们的意愿处理数据的custom processor。
<job id = "helloWorldJob"> 
   <step id = "step1"> 
      <tasklet> 
         <chunk reader = "mysqlReader" writer = "fileWriter" 
            processor = "CustomitemProcessor" ></chunk> 
      </tasklet> 
   </step> 
</ job>

Spring Batch提供了一长串readers和writers。使用这些预定义的类,我们可以为它们定义bean。我们将在接下来的章节中更详细地讨论读者和作者。

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

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

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

JobLauncher

JobLauncher是一个接口,它使用给定的一组参数启动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是执行作业/步骤的代表。它们包含作业/步骤的运行信息,例如(作业/步骤)的开始时间,(作业/步骤的)结束时间。

3 应用程序

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

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

配置文件

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

  • 该job和step定义。
  • 豆类定义readers和writers
  • 定义诸如JobLauncher,JobRepository,事务管理器和数据源等组件。

在我们的例子中,为了更好地理解,我们将它分成两个文件:job.xml文件(定义作业,步骤,读取器和写入器)和context.xml文件(作业启动器,作业存储库,事务管理器和数据源)。

Mapper类

根据读者,Mapper类实现了诸如行映射器,字段集映射器等接口。它包含从读取器获取数据并使用setter和getter方法(Java Bean)将其设置为Java类的代码,。

Java Bean类

具有setter和getters(Java bean)的Java类表示具有多个值的数据。它充当助手类。我们将把这个数据从一个组件(reader,writer,processer)传递给这个类的对象。

微进程/处理器

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

启动器类

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


spring boot批量删除百万数据 spring批量处理_批处理_03

4 配置

在编写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

它是工作的标识,必须指定该属性的值。

2

restartable

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

以下是SpringBatch作业的XML配置。


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


Step

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

S.No

属性和描述

1

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

它用于指定定义事务管理器的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用于配置数据源。这个bean与类型为org.springframework.jdbc.datasource.DriverManagerDataSource的类相关联。

S.No

属性和描述

1

driverClassName

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

2

url

这指定了数据库的URL。

3

username

这指定了连接数据库的用户名。

4

password

这指定了与数据库连接的密码。

以下是数据源的示例配置。

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

5 Readers, Writers & Processors

一个项目读取器数据读入来自特定源的弹簧批量应用,而一个项目写入器从Spring Batch的应用将数据写入到特定目的地。

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

一大块是的子元素微进程。它用于执行读取,写入和处理操作。我们可以在如下所示的步骤中配置使用此元素的读取器,写入器和处理器。

<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等各种文件系统/数据库的数据。

包括读者在你的应用程序,你需要定义为读者豆,到了豆中的所有必需的属性提供值,并通过ID等Bean作为值块元素的属性阅读器(同为作家)。

ItemReader

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

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

读者

目的

FlatFIleItemReader

从平面文件中读取数据。

StaxEventItemReader

从XML文件读取数据。

StoredProcedureItemReader

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

JDBCPagingItemReader

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

MongoItemReader

从MongoDB读取数据。

Neo4jItemReader

从Neo4jItemReader读取数据。

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

<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

这是写入数据的批处理步骤的要素。ItemWriter一次写入一个项目。Spring Batch提供了一个Interface ItemWriter。所有的作家都实现了这个接口。

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

作家

目的

FlatFIleItemWriter

将数据写入平面文件。

StaxEventItemWriter

将数据写入XML文件。

StoredProcedureItemWriter

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

JDBCPagingItemWriter

将数据写入关系数据库数据库。

MongoItemWriter

将数据写入MongoDB。

Neo4jItemWriter

将数据写入Neo4j。

同样,我们需要通过创建bean来配置ItemWriters。以下是将数据写入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>

项目处理器

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

微进程类 -当没有读取器和写入器给出,一个微进程充当SpringBatch的处理器。它只处理单个任务。

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

在批处理过程中,如果读取了“n”个记录或数据元素,那么对于每个记录,它将读取数据,处理数据并将数据写入写入器。为了处理数据,它在通过的处理器上进行中继。

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

以下是一个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; 
   } 
}

7 基本应用程序

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

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

  • 配置文件 - 这是一个XML文件,我们在其中定义作业和作业的步骤。(如果还涉及到读者和作家也一样,那么的配置读者和作家,也包括在此文件。)
  • Context.xml - 在这个文件中,我们将定义像作业存储库,作业启动器和事务管理器这样的bean。
  • Tasklet类 - 在这个类中,我们将编写处理代码作业(在这种情况下,它显示一个简单的消息)
  • Launcher类 - 在这个类中,我们将通过运行Job启动器来启动批处理应用程序。

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


8 XML到MySQL

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

阅读器 - 我们在应用程序中使用的阅读器是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>

作家 -的作家,我们正在使用的应用程序是JdbcBatchItemWriter将数据写入到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) 
);

处理器 - 我们在应用程序中使用的处理器是一个自定义处理器,它将每个记录的数据写入PDF文档。

在批处理过程中,如果读取了“n”个记录或数据元素,那么对于每个记录,它将读取数据,处理数据并将数据写入Writer。为了处理数据,它在通过的处理器上进行中继。在这种情况下,在自定义处理器类中,我们编写了代码来加载特定的PDF文档,创建新页面,以表格格式将数据项写入PDF。

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

jobConfig.xml

以下是我们的示例Spring Batch应用程序的配置文件。在这个文件中,我们将定义Job和步骤。除此之外,我们还为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

以下是处理器类。在这个类中,我们在应用程序中编写处理代码。在这里,我们正在加载一个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类。这是一个带有setter和getter方法的简单类。

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] 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表,它会向您显示以下输出 -

教程_id

教程_作者

教程_title

提交日期

教程_icon

教程_description

1001

桑杰

学习Java

2007年6月5日

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

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

1002

阿卜杜勒S

学习MySQL

19-04-2007

https://开头WWW。tutorialspoint.com / mysql / images /mysql-minilogo.jpg

MySQL是最受欢迎的开源关系SQL数据库管理系统。MySQL是用于开发基于Web的软件应用程序的最佳RDBMS之一。本教程将为您提供MySQL的快速入门,并让您熟悉MySQL编程。

1003

了解JavaFX

奎师那Kasyap

2017年6月7日

https://开头WWW。tutorialspoint.com / javafx / images / javafx-minilogo.jpg

MySQL是最受欢迎的开源关系SQL数据库管理系统。MySQL是用于开发基于Web的软件应用程序的最佳RDBMS之一。本教程将为您提供MySQL的快速入门,并让您熟悉MySQL编程。

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


spring boot批量删除百万数据 spring批量处理_spring_04

9 CSV到XML

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

阅读器 - 我们在应用程序中使用的阅读器是FlatFileItemReader,用于从CSV文件中读取数据。

以下是我们在此应用程序中使用的输入CSV文件。本文档包含指定详细信息的数据记录,如教程编号,教程作者,教程标题,提交日期,教程图标和教程描述。


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文件。

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

jobConfig.xml

以下是我们的示例Spring Batch应用程序的配置文件。在这个文件中,我们将定义Job和步骤。除此之外,我们还为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

以下是处理器类。在这个类中,我们在应用程序中编写处理代码。在这里,我们正在打印每条记录的内容。

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类

以下是Tutorial类。它是一个简单的带有setter和getter方法的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>


10 MySQL到XML

在本章中,我们将创建一个使用MySQL读取器和XML Writer的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文件。

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

以下是处理器类。在这个类中,我们在应用程序中编写处理代码。在这里,我们正在打印每条记录的内容。

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类。它是一个简单的带有setter和getter方法的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>

11 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)。

处理器 - 我们在应用程序中使用的处理器是一个自定义处理器,它只是打印从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,如作业存储库,作业启动器和事务管理器。

<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

以下是处理器类。在这个类中,我们在应用程序中编写处理代码。在这里,我们正在打印每条记录的内容。

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类。它是一个简单的带有setter和getter方法的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] 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]