这里我们重点学习一下springbatch里面的各种监听器的使用,以及job参数的传递。追求得到之日即其终止之时,寻觅的过程亦即失去的过程。

springbatch的监听器

一、JOB LISTENERS:监听job层面上的操作

public interface JobExecutionListener {
void beforeJob(JobExecution jobExecution);
void afterJob(JobExecution jobExecution);
}
  • 类方法的方式
<job id="helloWorldJob">
<listeners>
<listener ref="jobExecListener"/>
</listeners>
<step ....>
</step>
</job>

bean的定义

<bean id="jobExecListener" class="spring.batch.helloworld.JobExecListener"/>

bean的实现

package spring.batch.helloworld;

import org.springframework.batch.core.JobExecution;
import org.springframework.batch.core.JobExecutionListener; /**
* @Author: huhx
* @Date: 2017-11-02 上午 8:50
*/
public class JobExecListener implements JobExecutionListener { @Override
public void beforeJob(JobExecution jobExecution) {
System.out.println("before start time: " + jobExecution.getStartTime());
} @Override
public void afterJob(JobExecution jobExecution) {
System.out.println("after end time: " + jobExecution.getEndTime());
}
}
  • 使用注解方式,区别在于bean类的编写。
public class JobExecListener {

    @BeforeJob
public void beforeJob(JobExecution jobExecution) {
System.out.println("before start time: " + jobExecution.getStartTime());
} @AfterJob
public void afterJob(JobExecution jobExecution) {
System.out.println("after end time: " + jobExecution.getEndTime());
}
}

这个例子是基于helloworld的例子来的,可以参考博客:springbatch---->springbatch的使用(一).。以下是打印的结果

before start time: Thu Nov  :: CST
Hello
World!
after end time: Thu Nov :: CST

二、STEP LISTENERS:监听Step的处理过程

springbatch为我们提供了如下的关于Step的监听器。

、ChunkListener
Called before and after chunk execution
、ItemProcessListener
Called before and after an ItemProcessor gets an item and when that processor throws an exception
、ItemReadListener
Called before and after an item is read and when an
exception occurs reading an item
、ItemWriteListener
Called before and after an item is written and when an exception occurs writing an item
、SkipListener
Called when a skip occurs while reading, processing, or writing an item
、StepExecutionListener
Called before and after a step

Step监听器的接口,用法同上述的Job监听器基本一样。也是有方法的实现方式和注解的实现方式。

三、parent与abstract属性的使用

1、abstract
When true, specifies that the job or step element isn’t a concrete element but an abstract one used only for configuration. Abstract configuration enti-
ties aren’t instantiated.
2、parent: 子元素继承了父元素所有的属性,当然子元素可以复写父元素的属性
The parent element used to configure a given element. The child element has all properties of its parent and can override them.

在batch.xml文件中增加一个step和一个job。

<!--parent and abstract-->
<step id="parentStep" abstract="true">
<tasklet transaction-manager="transactionManager">
<listeners>
<listener ref="parentStepListener"/>
</listeners>
</tasklet>
</step> <job id="childJob">
<step id="childStep" parent="parentStep">
<tasklet ref="childTasklet" transaction-manager="transactionManager"/>
</step>
</job> <bean:bean id="childTasklet" class="spring.batch.parentAbstract.ParentTasklet" scope="step">
<bean:property name="username" value="#{jobParameters['password']}"/>
</bean:bean>

parentTasklet的实现类代码:

package spring.batch.parentAbstract;

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; /**
* @Author: huhx
* @Date: 2017-11-02 上午 9:18
*/
public class ParentTasklet implements Tasklet { private String username; public void setUsername(String username) {
this.username = username;
} @Override
public RepeatStatus execute(StepContribution contribution, ChunkContext chunkContext) throws Exception {
System.out.println("parent tasklet" + username);
return RepeatStatus.FINISHED;
}
}

打印的结果如下,可以看到childJob已经有了parentStep里面的监听器了。

before step.
parent tasklet123456
after step.

另外JobLaunch.java的代码如下

public class JobLaunch {
public static void main(String[] args) {
ApplicationContext context = new ClassPathXmlApplicationContext("config/batch/batch.xml");
JobLauncher launcher = (JobLauncher) context.getBean("jobLauncher"); Job job = (Job) context.getBean("childJob");
try {
// 运行Job
JobParametersBuilder parametersBuilder = new JobParametersBuilder();
JobParameters jobParameters = parametersBuilder.
addString("username", "linux").
addString("password", "123456").
toJobParameters();
launcher.run(job, jobParameters);
} catch (Exception e) {
e.printStackTrace();
}
}
}

有关于scope="step" 的解释,这里说明一下。

    The step scope means that Spring will create the bean only when the step asks for it and that values will be resolved then (this is the lazy instantiation pattern; the bean isn’t created during the Spring application context’s bootstrapping). To trigger the dynamic evaluation of a value, you must use the #{expression} syntax. The expression must be in Sp EL , which is available as of Spring 3.0.

四、关于ValidatingItemProcessor的一些理解

  它实现了ItemProcessor,用于chunk里面的processor属性。以下是它的一个用法。Simple implementation of ItemProcessor that validates input and returns it without modifications.

...
<batch:chunk reader="reader" processor="processor" writer="writer" commit-interval="100" skip-limit="5">
<batch:skippable-exception-classes>
<batch:include class="org.springframework.batch.item.validator.ValidationException"/>
</batch:skippable-exception-classes>
</batch:chunk>
.... <bean id="processor" class="org.springframework.batch.item.validator.ValidatingItemProcessor">
<property name="filter" value="false" />
<property name="validator">
<bean class="spring.batch.parentAbstract.ProductValidator" />
</property>
</bean>

ProductValidator的代码

import java.math.BigDecimal;
import org.springframework.batch.item.validator.ValidationException;
import org.springframework.batch.item.validator.Validator;
import com.manning.sbia.ch01.domain.Product; public class ProductValidator implements Validator<Product> {
@Override
public void validate(Product product) throws ValidationException {
if(BigDecimal.ZERO.compareTo(product.getPrice()) >= 0) {
throw new ValidationException("Product price cannot be negative!");
}
}
}

关于ValidatingItemProcessor的源代码,它有两个属性validator和filter 。

package org.springframework.batch.item.validator;

import org.springframework.batch.item.ItemProcessor;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.util.Assert; public class ValidatingItemProcessor<T> implements ItemProcessor<T, T>, InitializingBean { private Validator<? super T> validator; private boolean filter = false; public ValidatingItemProcessor() {} public ValidatingItemProcessor(Validator<? super T> validator) {
this.validator = validator;
} public void setValidator(Validator<? super T> validator) {
this.validator = validator;
} public void setFilter(boolean filter) {
this.filter = filter;
} @Override
public T process(T item) throws ValidationException {
try {
validator.validate(item);
}
catch (ValidationException e) {
if (filter) {
return null; // filter the item
}
else {
throw e; // skip the item
}
}
return item;
} @Override
public void afterPropertiesSet() throws Exception {
Assert.notNull(validator, "Validator must not be null.");
}
}

友情链接

springbatch---->springbatch的使用(四)的更多相关文章

  1. SpringBatch Sample (四)(固定长格式文件读写)

    前篇关于Spring Batch的文章,讲述了Spring Batch 对XML文件的读写操作. 本文将通过一个完整的实例,与大家一起讨论运用Spring Batch对固定长格式文件的读写操作.实例延 ...

  2. 年度Java技术盘点,懂这些技术的程序员2019发展大好

    与一年前一样,Java仍然是最流行的编程语言.据TIOBE的数据显示,几十年来,Java比其他语言更常名列榜首,Java因为它拥有可移植性.可扩展性和庞大的用户社区,所以许多知名互联网公司使用Java ...

  3. YII内置验证规则

    required: 必填字段验证, 来自 CRequiredValidator类的别名 array(‘字段名列表用逗号隔开’, ‘required’),    就这样的一个小小的写法,可以让字段前面加 ...

  4. Spring Batch介绍

    简介 SpringBatch 是一个大数据量的并行处理框架.通常用于数据的离线迁移,和数据处理,⽀持事务.并发.流程.监控.纵向和横向扩展,提供统⼀的接⼝管理和任务管理;SpringBatch是Spr ...

  5. springbatch操作CSV文件

    一.需求分析 使用Spring Batch对CSV文件进行读写操作: 读取一个含有四个字段的CSV文件(id, name, age, score), 对文件做简单的处理, 然后输出到还有一个csv文件 ...

  6. SpringBatch Sample (二)(CSV文件操作)

    本文将通过一个完整的实例,与大家一起讨论运用Spring Batch对CSV文件的读写操作.此实例的流程是:读取一个含有四个字段的CSV文件(ID,Name,Age,Score),对读取的字段做简单的 ...

  7. SpringBoot整合SpringBatch

    一.引入依赖 pom.xml <?xml version="1.0" encoding="UTF-8"?> <project xmlns=&q ...

  8. SpringBatch的核心组件JobLauncher和JobRepository

    Spring Batch的框架包括启动批处理作业的组件和存储Job执行产生的元数据.因此只需掌握配置这个基础框架在批处理应用程序中即启动Jobs并存储Job元数据. 组件:Job Launcher和J ...

  9. SpringBatch简介

    spring Batch是一个轻量级的.完善的批处理框架,旨在帮助企业建立健壮.高效的批处理应用.SpringBatch是Spring的一个子项目,使用Java语言并基于Spring框架为基础开发,使 ...

  10. spring-boot-oracle spring-batch

    Install/Configure Oracle express Oracle xe installer for linux (I don't care if you're running linux ...

随机推荐

  1. django学习2 视图和模板

    1 编写更多的视图 polls/views.py def detail(request, question_id): return HttpResponse("You're looking ...

  2. unity-----------------------使用BuildAssetBundle打包

      我发现很多美工兄弟都爱问程序Unity3d为什么总丢材质? 我不排除U3d有BUG的情况下会丢材质?但是其实很多时候是人为操作而引起的. 1.不保存就在上传 这个操作太恐怖了,切记!!在 U3D里 ...

  3. [poj 1947] Rebuilding Roads 树形DP

    Rebuilding Roads Time Limit: 1000MS Memory Limit: 30000K Total Submissions: 10653 Accepted: 4884 Des ...

  4. 回想sql语句中的各种连接

    1. 内连接(Inner Join) 内连接是最常见的一种连接,它页被称为普通连接,而E.FCodd最早称之为自然连接. 以下是ANSI SQL-92标准 select * from    t_ins ...

  5. R绘图系统边框详解

    在R语言的基础绘图系统中,有plot, figure, outer, inner 共4种边框: 这四种边框实际上明确了整个绘图设备的布局 1) outer,  当我们声明一个绘图设备的时候,outer ...

  6. yii2 使用阿里大鱼短信

    1.首先申请阿里账号 2.开通短信服务 3.短信签名 4.添加模板 以上4步是前期工作 -------------------------------------------------------- ...

  7. Win7-64位安装TensorFlow-GPU

    1.查看电脑显卡 路径:计算机--属性--设备管理器-显示适配器 2.显卡(GPU)是否支持CUDN https://developer.nvidia.com/cuda-gpus 3.安装 1)CUD ...

  8. Mac下终端使用密钥登录服务器

    可行方法: mac终端输入 ssh-keygen 因为mac系统是类unix系统,linux系统是unix系统演变来的,所以呢,相当于在一个linux系统登录另外一个linux系统, 基本命令还是一样 ...

  9. Linux 目录下属性查看操作

    1. 查看当前目录所有文件和文件夹的大小 方法一: $du -sh * 或 $du -h -d 0 * '-d 0' 代表查询目录的深度为0 ,也就是当前目录,'-d 3' 表示文件目录深度为3,可以 ...

  10. JS组件系列——表格组件神器:bootstrap table 包含了js对象的定义和对象成员函数的定义

    前言:之前一直在忙着各种什么效果,殊不知最基础的Bootstrap Table用法都没有涉及,罪过,罪过.今天补起来吧.上午博主由零开始自己从头到尾使用了一遍Bootstrap Table ,遇到不少 ...