Spring Batch之作业步Step的抽象与继承(十二)

        Spring Batch框架支持抽象的Step定义和Step的继承特性。通过定义抽象的Step可以将Step的共性进行抽取,形成父类的Step定义;然后各个具体的Step可以继承父类Step的特性,并定义自己的属性。

一、抽象Step

        通过abstract属性可以指定Step为抽象的Step。抽象的Step不能被实例化,只能作为其他Step的父类。通常可以在抽象的Step中定义全局性的配置,供子类使用。

<!--定义一个抽象的Step-->
<batch:step id="abstractParentStep" abstract="true">
    <batch:tasklet>
        <batch:chunk commit-interval="10"/>
    </batch:tasklet>
</batch:step>

二、继承Step

        通过parent属性可以指定当前的Step的父类,类似于Java中的继承一样,子类Step具有父类中定义的所有属性能力。子类继承时候,可以从抽象Step继承,也可以从普通的Step中继承。

<!--定义一个抽象的Step-->
<batch:step id="abstractParentStep" abstract="true">
    <batch:tasklet>
        <batch:chunk commit-interval="10"/>
    </batch:tasklet>
</batch:step>

<!--定义一个Step,继承abstractParentStep-->
<batch:step id="parentStep" parent="abstractParentStep">
    <batch:tasklet transaction-manager="transactionManager" allow-start-if-complete="true">
        <!-- 使用abstractParentStep的commit-interval属性 -->
        <batch:chunk reader="csvItemReader" writer="csvItemWriter"/>
    </batch:tasklet>
</batch:step>

三、项目举例

1.项目框架

2.代码实现

CreditBill.java:

package com.xj.demo10;

/**
 * @Author : xjfu
 * @Date : 2021/10/26 19:27
 * @Description :
 */
public class CreditBill {
    //银行卡账户ID
    private String accountID = "";
    //持卡人姓名
    private String name = "";
    //消费金额
    private double amount = 0;
    //消费日期
    private String date = "";
    //消费场所
    private String address = "";

   //get和set方法

    @Override
    public String toString() {
        return this.accountID + "," + this.name + "," + this.amount + "," + this.date + "," + this.address;
    }
}

CreditBillProcessor.java:

package com.xj.demo10;

import org.springframework.batch.item.ItemProcessor;

import java.util.Date;

/**
 * @Author : xjfu
 * @Date : 2021/10/26 19:29
 * @Description :
 */
public class CreditBillProcessor implements ItemProcessor<CreditBill, CreditBill> {
    @Override
    public CreditBill process(CreditBill bill) throws Exception {

        System.out.println(bill.toString());
        //做一些简单的处理
        bill.setAccountID(bill.getAccountID() + "1");
        bill.setName(bill.getName() + "2");
        bill.setAmount(bill.getAmount() + 3);
        bill.setDate(new Date().toString());
        bill.setAddress(bill.getAddress() + 5);

        return bill;
    }
}

Demo10BatchMain.java:

package com.xj.demo10;

import org.springframework.batch.core.Job;
import org.springframework.batch.core.JobExecution;
import org.springframework.batch.core.JobParameters;
import org.springframework.batch.core.JobParametersBuilder;
import org.springframework.batch.core.launch.JobLauncher;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
/**
 * @Author : xjfu
 * @Date : 2021/12/8 8:52
 * @Description :Step的抽象与继承
 */
public class Demo10BatchMain {

    public static void main(String[] args) {
        Demo10BatchMain batchMain = new Demo10BatchMain();
        batchMain.executeJob("demo10/job/demo10-job.xml", "billJob", "jobLauncher", new JobParametersBuilder().toJobParameters());
    }

    /**
     *执行Job
     * @param jobXmlPath 配置job的xml文件路径
     * @param jobId job的id
     * @param jobLauncherId jobLauncher的id
     * @param jobParameters 参数
     */
    public void executeJob(String jobXmlPath, String jobId, String jobLauncherId, JobParameters jobParameters){
        ApplicationContext context = new ClassPathXmlApplicationContext(jobXmlPath);
        JobLauncher jobLauncher = (JobLauncher) context.getBean(jobLauncherId);
        //获取要执行的Job
        Job job = (Job)context.getBean(jobId);

        try{
            //开始执行作业Job
            JobExecution jobExecution =  jobLauncher.run(job, jobParameters);
            //输出执行结果
            System.out.println(jobExecution.toString());
        }catch (Exception e){
            e.printStackTrace();
        }
    }
}

demo10-inputFile.csv:

4101231234656,tom,100.00,2013-12-31 12:00:08,Lu lit
4101236543210,tom,120.00,2013-12-31 12:00:08,Lu Zui

demo10-job.xml:

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:batch="http://www.springframework.org/schema/batch"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/batch http://www.springframework.org/schema/batch/spring-batch.xsd">

    <!--导入文件-->
    <import resource="classpath:demo10/job/demo10-jobContext.xml"/>

    <!--定义一个抽象的Step-->
    <batch:step id="abstractParentStep" abstract="true">
        <batch:tasklet>
            <batch:chunk commit-interval="10"/>
        </batch:tasklet>
    </batch:step>

    <!--定义一个Step,继承abstractParentStep-->
    <batch:step id="parentStep" parent="abstractParentStep">
        <batch:tasklet transaction-manager="transactionManager" allow-start-if-complete="true">
            <!-- 使用abstractParentStep的commit-interval属性 -->
            <batch:chunk reader="csvItemReader" writer="csvItemWriter"/>
        </batch:tasklet>
    </batch:step>

    <!--定义名字为billJob的作业-->
    <batch:job id="billJob">
        <!--定义一个Step,继承parentStep-->
        <batch:step id="billStep" parent="parentStep">
            <batch:tasklet transaction-manager="transactionManager">
                <!--使用parentStep定义的读、写操作,使用自己定义的处理操作和commit-interval属性-->
                <batch:chunk processor="creditBillProcessor" commit-interval="2">
                </batch:chunk>
            </batch:tasklet>
        </batch:step>
    </batch:job>
</beans>

说明:通过配置文件可以看出,billJob使用的是自己的“commit-interval=2”的属性,而不是abstractParentStep的“commit-interval=10”属性,因为自己配置了commit-interval,所以覆盖了abstractParentStep的commit-interval;使用的parentStep的“reader”和“writer”,使用自己的“processor”。

demo10-jobContext.xml:

<?xml version="1.0" encoding="UTF-8"?>
<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.xsd">

    <!--定义作业仓库 Job执行期间的元数据存储在内存中-->
    <bean id="jobRepository" class="org.springframework.batch.core.repository.support.MapJobRepositoryFactoryBean">
    </bean>

    <!--定义作业调度器,用来启动job-->
    <bean id="jobLauncher" class="org.springframework.batch.core.launch.support.SimpleJobLauncher">
        <!--注入jobRepository-->
        <property name="jobRepository" ref="jobRepository"/>
    </bean>

    <!--定义事务管理器,用于Spring Batch框架中对数据操作提供事务能力-->
    <bean id="transactionManager" class="org.springframework.batch.support.transaction.ResourcelessTransactionManager"/>

    <!--读取信用卡账单文件,CSV 格式-->
    <!--使用FlatFileItemReader读文本文件-->
    <bean id="csvItemReader" class="org.springframework.batch.item.file.FlatFileItemReader" scope="step">
        <!--指定读取的资源文件-->
        <property name="resource" value="classpath:demo10/data/demo10-inputFile.csv"/>
        <!--通过lineMapper把文本中的一行转换为领域对象creditBill-->
        <property name="lineMapper">
            <bean class="org.springframework.batch.item.file.mapping.DefaultLineMapper">
                <!--lineTokenizer定义文本中每行的分隔符号-->
                <property name="lineTokenizer" ref="lineTokenizer"/>
                <!--fieldSetMapper定义了转换结果映射,即具体映射到哪个Java类对象-->
                <property name="fieldSetMapper">
                    <bean class="org.springframework.batch.item.file.mapping.BeanWrapperFieldSetMapper">
                        <property name="prototypeBeanName" value="creditBill"/>
                    </bean>
                </property>
            </bean>
        </property>
    </bean>

    <!--lineTokenizer-->
    <bean id="lineTokenizer" class="org.springframework.batch.item.file.transform.DelimitedLineTokenizer">
        <!--按","符号对行进行切割-->
        <property name="delimiter" value=","/>
        <!--属性名称列表,将切割后的行按顺序投入-->
        <property name="names">
            <list>
                <value>accountID</value>
                <value>name</value>
                <value>amount</value>
                <value>date</value>
                <value>address</value>
            </list>
        </property>
    </bean>

    <!--注入实体类-->
    <bean id="creditBill" class="com.xj.demo10.CreditBill" scope="prototype"></bean>

    <!--数据处理类-->
    <bean id="creditBillProcessor" class="com.xj.demo10.CreditBillProcessor" scope="step"></bean>

    <!--写信用卡账单文件,CSV格式-->
    <bean id="csvItemWriter" class="org.springframework.batch.item.file.FlatFileItemWriter" scope="step">
        <!--要写入的文件位置,因为[classpath:]不是一个具体的目录,这里应当用[file:](从项目根目录开始)指明输出位置-->
        <property name="resource" value="file:src/main/resources/demo10/data/demo10-outputFile.csv"/>
        <!--[lineAggregator成员]指明行聚合器,用来将对象输出到文件时构造文件中的每行的格式-->
        <property name="lineAggregator">
            <!--这里使用Spring Batch自带的DelimitedLineAggregator来作为行聚合器(可以拼接一个个属性形成行)-->
            <bean class="org.springframework.batch.item.file.transform.DelimitedLineAggregator">
                <!--使用","拼接-->
                <property name="delimiter" value=","/>
                <!--fieldExtractor成员用来将Java类的属性组成的数组拼接成行字符串-->
                <property name="fieldExtractor">
                    <bean class="org.springframework.batch.item.file.transform.BeanWrapperFieldExtractor">
                        <property name="names" value="accountID,name,amount,date,address">
                        </property>
                    </bean>
                </property>
            </bean>
        </property>
    </bean>
</beans>

3.运行结果

成功写入demo10-outputFile.csv: 

控制台输出:

 

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值