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

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

Spring批 本教程将使用在我们的第二批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 {

	@Autowired
	private JobBuilderFactory jobs;

	@Autowired
	private 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" />
@Bean
    public 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并将其加载到应用程序上下文中。

@Bean
	public ItemProcessor<TickerData, TickerData> processor() {
		return new TickerPriceProcessor();
	}

	@Bean
	public 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>
@Bean
	public Job TickerPriceConversion() throws MalformedURLException {
		return jobs.get("TickerPriceConversion").start(convertPrice()).build();
	}

	@Bean
    	public 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 {

	@Autowired
	private JobBuilderFactory jobs;

	@Autowired
	private StepBuilderFactory steps;

	@Bean
    public 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;
    }

	@Bean
	public ItemProcessor<TickerData, TickerData> processor() {
		return new TickerPriceProcessor();
	}

	@Bean
	public ItemWriter<TickerData> writer() {
		return new LogItemWriter();
	}

	@Bean
	public Job TickerPriceConversion() throws MalformedURLException {
		return jobs.get("TickerPriceConversion").start(convertPrice()).build();
	}

	@Bean
    public 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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值