最近,我协助一个客户启动并运行了Spring Batch实现。 该团队决定继续使用针对批处理作业的基于JavaConfig的配置,而不是传统的基于XML的配置。 随着这越来越成为配置Java应用程序的一种常用方法,我觉得是时候更新Keyhole的Spring Batch系列了 ,向您展示如何将现有的基于XML的Spring Batch配置转换为基于JavaConfig批注的新配置。

本教程将使用在我们的第二批Spring教程( https://keyholesoftware.com/2012/06/25/getting-started-with-spring-batch-part-two/ )中找到的简单批处理作业。

房子清洁

在开始转换过程之前,我们需要对项目进行一些房屋清洁。

  1. 尚未将Java构建和Spring环境升级到Java 7。
  2. 将Spring Boot依赖项添加到Maven pom.xml:
  3. <dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-batch</artifactId><version>1.2.4.RELEASE</version>
    </dependency>
  4. 将Spring Batch版本修改为3.0.4.RELEASE,并将Spring Framework版本修改为4.1.6.RELEASE
    <properties>                              <spring.framework.version>4.1.6.RELEASE</spring.framework.version><spring.batch.version>3.0.4.RELEASE</spring.batch.version>
    </properties>
  5. 在名为module-context.xml的原始批处理配置文件中注释掉作业定义。
  6. 在名为launch-context.xml的配置文件中注释掉Spring应用程序上下文配置元素。
  7. 注释掉Reader,Processor和Writer元素上的@Component批注。 不要注释掉CurrencyConversionServiceImpl类上的@Service批注。

构建基于JavaConfig的配置

现在我们已经删除或禁用了现有的基于XML的配置,我们可以开始构建基于JavaConfig的配置。 为此,我们需要创建一个带有一些注释的新类,这些注释为配置奠定了基础。

package com.keyhole.example.config;import org.springframework.batch.core.configuration.annotation.EnableBatchProcessing;
import org.springframework.batch.core.configuration.annotation.JobBuilderFactory;
import org.springframework.batch.core.configuration.annotation.StepBuilderFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;@Configuration
@EnableBatchProcessing
public class TickerPriceConversionConfig {@Autowiredprivate JobBuilderFactory jobs;@Autowiredprivate StepBuilderFactory steps;}

@Configuration注释使Spring容器知道该类将包含一个或多个@Bean注释的方法,这些方法将在运行时进行处理以生成Bean定义和服务请求。

@EnableBatchProcessing批注提供了用于构建批处理作业配置的基本配置。 Spring Batch使用此注释来设置默认的JobRepository,JobLauncher,JobRegistry,PlatformTransactionManager,JobBuilderFactory和StepBuilderFactory。

现在是时候为组成批处理作业的组件添加@Bean注释的方法了。 作为参考,我为每个bean提供了相应的XML配置。

ItemReader配置

<bean name="tickerReader"class="org.springframework.batch.item.file.FlatFileItemReader">
<property name="resource"
value="http://finance.yahoo.com/d/quotes.csv?s=XOM+IBM+JNJ+MSFT&f=snd1ol1p2" /><property name="lineMapper" ref="tickerLineMapper" />
</bean><bean name="tickerLineMapper"
class="org.springframework.batch.item.file.mapping.DefaultLineMapper">
<property name="fieldSetMapper" ref="tickerMapper" /><property name="lineTokenizer" ref="tickerLineTokenizer" />
</bean><bean name="tickerLineTokenizer"
class="org.springframework.batch.item.file.transform.DelimitedLineTokenizer" />
@Beanpublic ItemReader<TickerData> reader() throws MalformedURLException {FlatFileItemReader<TickerData> reader = new FlatFileItemReader<TickerData>();reader.setResource(new UrlResource("http://finance.yahoo.com/d/quotes.csv?s=XOM+IBM+JNJ+MSFT&f=snd1ol1p2"));reader.setLineMapper(new DefaultLineMapper<TickerData>() {{setLineTokenizer(new DelimitedLineTokenizer());setFieldSetMapper(new TickerFieldSetMapper());}});return reader;}

ItemProcessor和ItemWriter以前使用Spring容器的@Component注释来拾取bean并将其加载到应用程序上下文中。

@Beanpublic ItemProcessor<TickerData, TickerData> processor() {return new TickerPriceProcessor();}@Beanpublic ItemWriter<TickerData> writer() {return new LogItemWriter();}

现在我们已经定义了Spring bean,我们可以创建@Bean注释的方法来表示步骤和工作。 作为参考,我包括了相应的XML配置。

<batch:job id="TickerPriceConversion"><batch:step id="convertPrice"><batch:tasklet transaction-manager="transactionManager"><batch:chunk reader="tickerReader"processor="tickerPriceProcessor"writer="tickerWriter" commit-interval="10" /></batch:tasklet></batch:step></batch:job>
@Beanpublic Job TickerPriceConversion() throws MalformedURLException {return jobs.get("TickerPriceConversion").start(convertPrice()).build();}@Beanpublic Step convertPrice() throws MalformedURLException {return steps.get("convertPrice").<TickerData, TickerData> chunk(5).reader(reader()).processor(processor()).writer(writer()).build();}

我将在文章的末尾包含TickerPriceConversionConfig类的完整代码,以供参考,但基本上这就是全部!

一旦定义了Spring bean并使用JobBuilderFactory和StepBuilderFactory为批处理作业和步骤创建Bean配置,就可以运行该作业并测试配置了。 为了运行作业,我们将使用Spring Boot来测试新转换的作业配置的执行情况。 为此,我们将在测试包中创建一个名为TickerPriceConversionJobRunner的新类。

源代码如下所示:

package com.keyhole.example;import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;@SpringBootApplication
public class TickerPriceConversionJobRunner {public static void main(String[] args) {SpringApplication.run(TickerPriceConversionJobRunner.class, args);}}

@SpringBootApplication注释本质上是一个便捷注释,它提供了通常使用@ Configuration,@ EnableAutoConfiguration和@ComponentScan可以获得的功能。 TickerPriceConversionJobRunner是一个简单的Java应用程序,它将主要方法处理委托给Spring Boot的SpringApplication类来运行该应用程序。

现在,您可以将该项目导出为jar并从命令行运行TickerPriceConversionJobRunner,或者,如果您想在Spring STS中运行它,则可以右键单击该类,然后选择Run As→Spring Boot Application。

最终想法和代码清单

如您所见,创建Spring Batch作业配置并不需要很多工作,但是如果您决定将所有现有作业从基于XML的配置转换为较新的基于JavaConfig的配置,摆在您前面的工作。 大部分工作将花费大量时间来充分回归测试转换后的批处理作业。

如果您拥有大量的Spring Batch作业库,那将值得吗? 可能不是,但是如果您刚开始使用或具有可管理的批处理库,那么这绝对是我会采用的方法。

TickerPriceConversionConfig的代码清单

package com.keyhole.example.config;import java.net.MalformedURLException;import org.springframework.batch.core.Job;
import org.springframework.batch.core.Step;
import org.springframework.batch.core.configuration.annotation.EnableBatchProcessing;
import org.springframework.batch.core.configuration.annotation.JobBuilderFactory;
import org.springframework.batch.core.configuration.annotation.StepBuilderFactory;
import org.springframework.batch.item.ItemProcessor;
import org.springframework.batch.item.ItemReader;
import org.springframework.batch.item.ItemWriter;
import org.springframework.batch.item.file.FlatFileItemReader;
import org.springframework.batch.item.file.mapping.DefaultLineMapper;
import org.springframework.batch.item.file.transform.DelimitedLineTokenizer;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.UrlResource;import com.keyhole.example.LogItemWriter;
import com.keyhole.example.TickerData;
import com.keyhole.example.TickerFieldSetMapper;
import com.keyhole.example.TickerPriceProcessor;@Configuration
@EnableBatchProcessing
public class TickerPriceConversionConfig {@Autowiredprivate JobBuilderFactory jobs;@Autowiredprivate StepBuilderFactory steps;@Beanpublic ItemReader<TickerData> reader() throws MalformedURLException {FlatFileItemReader<TickerData> reader = new FlatFileItemReader<TickerData>();reader.setResource(new UrlResource("http://finance.yahoo.com/d/quotes.csv?s=XOM+IBM+JNJ+MSFT&f=snd1ol1p2"));reader.setLineMapper(new DefaultLineMapper<TickerData>() {{setLineTokenizer(new DelimitedLineTokenizer());setFieldSetMapper(new TickerFieldSetMapper());}});return reader;}@Beanpublic ItemProcessor<TickerData, TickerData> processor() {return new TickerPriceProcessor();}@Beanpublic ItemWriter<TickerData> writer() {return new LogItemWriter();}@Beanpublic Job TickerPriceConversion() throws MalformedURLException {return jobs.get("TickerPriceConversion").start(convertPrice()).build();}@Beanpublic Step convertPrice() throws MalformedURLException {return steps.get("convertPrice").<TickerData, TickerData> chunk(5).reader(reader()).processor(processor()).writer(writer()).build();}
}

TickerPriceConversionJobRunner的代码清单

  • 代码项目
package com.keyhole.example;import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;@SpringBootApplication
public class TickerPriceConversionJobRunner {public static void main(String[] args) {SpringApplication.run(TickerPriceConversionJobRunner.class, args);}}

翻译自: https://www.javacodegeeks.com/2015/07/spring-batch-replacing-xml-job-configuration-with-javaconfig.html

Spring Batch –用JavaConfig替换XML作业配置相关推荐

  1. Spring Batch –使用JavaConfig替换XML作业配置

    我最近协助一个客户启动并运行了Spring Batch实现. 该团队决定继续为批处理作业使用基于JavaConfig的配置,而不是传统的基于XML的配置. 随着这越来越成为配置Java应用程序的一种常 ...

  2. spring batch (四) Job的配置及配置文件说明介绍

    内容来自<Spring Batch 批处理框架>,作者:刘相. 我只是个搬运工. 一.Spring Batch提供了独立的标签用来顶一个Job配置,分别是job.step.tasklet. ...

  3. java spring bean配置文件_Spring基于xml文件配置Bean过程详解

    这篇文章主要介绍了spring基于xml文件配置Bean过程详解,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下 通过全类名来配置: class:be ...

  4. Spring框架IOC基础及XML的配置 第二章

    1 Spring概述 1.1 关于框架 框架的概念 框架:特指软件框架,它是我们在实际开发中解决项目需求的技术集合.运用框架可以大大简化代码的编写,缩短开发周期.同时,对后续负责项目维护的人员降低技术 ...

  5. spring+hibernate:在applicationCOntext.XML中配置C3P0参数说明

    背景: 在项目中遇到下面这个exception Exception occurred while logging on hibernate operation: Cannot open connect ...

  6. spring结合时,web.xml的配置

    <!-- 1. web.xml配置 <context-param> <param-name>webAppRootKey</param-name> <pa ...

  7. 四 Spring的工厂类,xml的配置

    Spring工厂类的结构图: BeanFactory:老版本的工厂类 BeanFactory:调用getBean的时候,才会生产类的实例 ApplicationFactory:新版本的工厂类 加载配置 ...

  8. spring整合hibernate的applicationContext.xml文件配置以及web.xml

    applicationContext.xml文件 <?xml version="1.0" encoding="UTF-8"?> <beans ...

  9. spring +springmvc+mybatis组合springmvc.xml文件配置

    <?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.sp ...

最新文章

  1. 困难样本挖掘(Online Hard Sample Mining)
  2. php获取当前时间的毫秒数,并且利用它测试代码段执行时间
  3. IPv6环境下路由器支持域名登录
  4. Buck开关电源拓扑结构分析
  5. python-windows安装相关问题
  6. 作者:杜小勇(1963-),男,中国人民大学信息学院教授,博士生导师。
  7. java迷宫类编程题_第十届蓝桥杯省赛java类B组 试题 E:迷宫 (动态规划之回溯法)...
  8. WebStorm如何设置默认游览器
  9. 如何解决api接口的并发问题?
  10. Centos安装php高版本
  11. 猎豹网校 ASP.NET全套教程
  12. Hello designer|PPT笔记
  13. web前端开发工程师面试题大全
  14. java计算机毕业设计无线通信基站监控及管理系统源码+系统+数据库+lw文档+mybatis+运行部署
  15. 对比Windows Phone与iOS、Android开发的不同[转]
  16. 树莓派有can通信吗_树莓派 RS485 CAN HAT模块使用
  17. 我在著名的外企工作多年
  18. 软件测试阶段划分以及测试分类
  19. matlab 分图 总标题,matlab中figure有多个图时,设定总标题的方法
  20. Mysql数据库经验总结

热门文章

  1. P5091-[模板]欧拉定理
  2. nssl1319-埃雷萨拉斯寻宝【SPFA,建图】
  3. ssl提高组周六备考赛【2018.10.27】
  4. 【图论】【并查集】矩形(ssl 1222)
  5. 2-sat模板- 输出可行解
  6. hive命令出现问题Failed with exception Java.io.IOException:java.lang.IllegalArgumentException: java.NET.URI
  7. div中的table内容过多时不超出div的范围解决方法
  8. java正则表达式中的坑String.matches(regex)、Pattern.matches(regex, str)和Matcher.matches()
  9. art-template入门(六)之解析规则
  10. Linux Tomcat安装