Spring Batch 之 Sample(XML文件操作)(五)

 

The original website:http://www.cnblogs.com/gulvzhe/archive/2011/12/03/2274908.html

前篇关于Spring Batch的文章,讲述了Spring Batch 对CSV文件的读写操作。 本文将通过一个完整的实例,与大家一起讨论运用Spring Batch对XML文件的读写操作。实例流程是从一个XML文件中读取商品信息,经过简单的处理,写入另外一个XML文件中。

     工程结构如下图:

                      

     log4j.xml是log处理的配置文件,与本文没有必然联系,再此不做论述。

     application.xml文件内容如下:

 1 <?xml version="1.0" encoding="UTF-8"?>
 2 <beans xmlns="http://www.springframework.org/schema/beans"
 3     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p"
 4     xmlns:tx="http://www.springframework.org/schema/tx" xmlns:aop="http://www.springframework.org/schema/aop"
 5     xmlns:context="http://www.springframework.org/schema/context"
 6     xsi:schemaLocation="http://www.springframework.org/schema/beans  
 7 http://www.springframework.org/schema/beans/spring-beans-3.0.xsd  
 8 http://www.springframework.org/schema/tx  
 9 http://www.springframework.org/schema/tx/spring-tx-3.0.xsd  
10 http://www.springframework.org/schema/aop  
11 http://www.springframework.org/schema/aop/spring-aop-3.0.xsd  
12 http://www.springframework.org/schema/context  
13 http://www.springframework.org/schema/context/spring-context-2.5.xsd"
14     default-autowire="byName">
15 
16     <!-- auto scan path -->
17     <context:component-scan base-package="com.wanggc.springbatch.sample.xml" />
18 
19     <bean id="jobLauncher"
20         class="org.springframework.batch.core.launch.support.SimpleJobLauncher">
21         <property name="jobRepository" ref="jobRepository" />
22     </bean>
23 
24     <bean id="jobRepository" class="org.springframework.batch.core.repository.support.MapJobRepositoryFactoryBean" />
25 
26     <bean id="transactionManager"
27         class="org.springframework.batch.support.transaction.ResourcelessTransactionManager">
28     </bean>
29 </beans>

     17行是base-spckage的指定,是spring的用法。

     19-22行配置的jobLauncher用来启动Job。

     24行配置的jobRepository为job提供持久化操作。

     26-28行的transactionManager提供事物管理操作。

     本文核心配置文件batch.xml内容如下:

 1 <?xml version="1.0" encoding="UTF-8"?>
 2 <bean:beans xmlns="http://www.springframework.org/schema/batch"
 3     xmlns:bean="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 4     xmlns:p="http://www.springframework.org/schema/p" xmlns:tx="http://www.springframework.org/schema/tx"
 5     xmlns:aop="http://www.springframework.org/schema/aop" xmlns:context="http://www.springframework.org/schema/context"
 6     xmlns:util="http://www.springframework.org/schema/util"
 7     xsi:schemaLocation="http://www.springframework.org/schema/beans 
 8 http://www.springframework.org/schema/beans/spring-beans-3.0.xsd  
 9 http://www.springframework.org/schema/tx 
10 http://www.springframework.org/schema/tx/spring-tx-3.0.xsd  
11 http://www.springframework.org/schema/aop 
12 http://www.springframework.org/schema/aop/spring-aop-3.0.xsd  
13 http://www.springframework.org/schema/context 
14 http://www.springframework.org/schema/context/spring-context-2.5.xsd
15 http://www.springframework.org/schema/batch 
16 http://www.springframework.org/schema/batch/spring-batch-2.1.xsd 
17 http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util.xsd">
18 
19     <bean:import resource="applicationContext.xml" />
20 
21     <job id="xmlFileReadAndWriterJob">
22         <step id="xmlFileReadAndWriterStep">
23             <tasklet>
24                 <chunk reader="xmlReader" writer="xmlWriter" processor="xmlProcessor"
25                     commit-interval="10">
26                 </chunk>
27             </tasklet>
28         </step>
29     </job>
30 
31     <!-- XML文件读取 -->
32     <bean:bean id="xmlReader"
33         class="org.springframework.batch.item.xml.StaxEventItemReader" scope="step">
34         <bean:property name="fragmentRootElementName" value="goods" />
35         <bean:property name="unmarshaller" ref="tradeMarshaller" />
36         <bean:property name="resource"
37             value="file:#{jobParameters['inputFilePath']}"></bean:property>
38     </bean:bean>
39 
40     <!-- XML文件写入 -->
41     <bean:bean id="xmlWriter"
42         class="org.springframework.batch.item.xml.StaxEventItemWriter" scope="step">
43         <bean:property name="rootTagName" value="wanggc" />
44         <bean:property name="marshaller" ref="tradeMarshaller" />
45         <bean:property name="resource"
46             value="file:#{jobParameters['outputFilePath']}" />
47     </bean:bean>
48 
49     <bean:bean id="tradeMarshaller"
50         class="org.springframework.oxm.xstream.XStreamMarshaller">
51         <bean:property name="aliases">
52             <util:map id="aliases">
53                 <bean:entry key="goods"
54                     value="com.wanggc.springbatch.sample.xml.pojo.Goods" />
55                 <bean:entry key="buyDay" value="java.util.Date"></bean:entry>
56             </util:map>
57         </bean:property>
58     </bean:bean>
59 </bean:beans>

     21-29行配置了Job的基本信息。此Job包含一个Step,Step中包含了基本的读(xmlReader),处理(xmlProcessor),写(xmlWriter)。

     32-38行配置了对XML文件读操作。对XML的读是由SpringBatch提供的StaxEventItemReader类来完成。要读取一个XML文件,首先要知道这个文件的存放路径,resource属性就是指定文件路径信息的。知道了文件路径,还需要知道要读取的XML的根节点名称,fragmentRootElementName属性就是指定根节点名称的。知道了根节点名称,还需要知道的一点就是怎么解析这个节点信息,unmarshaller就负责完成解析节点信息,并映射成程序pojo对象。注意,根节点并不是指整个XML文件的根节点,而是指要读取的信息片段的根节点,不管这个节点片段处在哪一层,框架都会遍历到。

     49-58行配置了解析XML节点信息的unmarshaller。其中entry的key指定对应根节点名称goods,value指定程序的pojo类,这样,程序就可以将goods节点下的子节点与pojo类(Goods)中的属性去匹配,当匹配到子节点名与pojo类中的属性名相同时,就会将子节点的内容赋值给pojo类的属性。这样就完成了一个根节点的读取,框架会控制循环操作,直到将文件中所有根(goods)节点全部读完为止。这样就完成了XML文件的读操作。

     41-47行配置了对XML文件的写操作。与读XML文件一样,要写一个XML文件,也是需要知道这个文件的文件的存放路径的,同样是resource属性提供文件的路径信息。同时,也是需要知道这个文件的跟节点信息的,rootTagName属性提供根节点名信息。注意此处的根节点,指整个文件的跟节点,与读得时候稍有区别,从两个属性的名称上也可以看出。有了上面的信息,完成一个写操作,还需要一个把pojo对象转换成XML片段的工具,由marshaller提供。本文读操作的unmarshaller和写操作的marshaller用的是同一个转换器,因为XStreamMarshaller既提供将节点片段转换为pojo对象功能,同时又提供将pojo对象持久化为xml文件的功能。如果写的内容与读得内容有很大差异,可以另外配置一个转换器。

     batch.xml文件配置的对XML文件的读写操作,至于读出来的信息做怎么样的处理再写入文件,通过简单的配置恐怕就无法完成了,就需要我们自己写代码完成了。XMLProcessor类就是完成这个工作的。只要在Job的配置文件中指定到这个类就可以了。XMLProcessor类的内容如下:

package com.wanggc.springbatch.sample.xml;

import java.util.Date;

import org.springframework.batch.item.ItemProcessor;
import org.springframework.stereotype.Component;

import com.wanggc.springbatch.sample.xml.pojo.Goods;

/**
 * XML文件处理类。
 */
@Component("xmlProcessor")
public class XMLProcessor implements ItemProcessor<Goods, Goods> {

    /**
     * XML文件内容处理。
     * 
     */
    @Override
    public Goods process(Goods goods) throws Exception {
        // 购入日期变更
        goods.setBuyDay(new Date());
        // 顾客信息变更
        goods.setCustomer(goods.getCustomer() + "顾客!");
        // ISIN变更
        goods.setIsin(goods.getIsin() + "IsIn");
        // 价格变更
        goods.setPrice(goods.getPrice() + 1000.112);
        // 数量变更
        goods.setQuantity(goods.getQuantity() + 100);
        // 处理后的数据返回
        return goods;
    }
}

     内容很简单,再此就不做赘述了。要注意的一点就是红背景色的地方。加了此标签无须在batch.xml文件增加对xmlProcessor声明用的bean,可以在job中直接引用,这是Spring的功能。当然,实现这个的前提是要在applicationContext.xml中配置base-package,只有这样才能找到。

     工程结构图中的XMLLaunch类用来启动Job。内容如下:

package com.wanggc.springbatch.sample.xml;

import org.springframework.batch.core.Job;
import org.springframework.batch.core.JobExecution;
import org.springframework.batch.core.JobParametersBuilder;
import org.springframework.batch.core.launch.JobLauncher;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class XMLLaunch {

    /**
     * @param args
     */
    public static void main(String[] args1) {

        ApplicationContext context = new ClassPathXmlApplicationContext(
                "batch.xml");
        JobLauncher launcher = (JobLauncher) context.getBean("jobLauncher");
        Job job = (Job) context.getBean("xmlFileReadAndWriterJob");

        try {
            // JOB实行
            JobExecution result = launcher.run(job, new JobParametersBuilder()
                    .addString("inputFilePath", "C:\\input.xml")
                    .addString("outputFilePath", "C:\\output.xml")
                    .toJobParameters());
            // 运行结果输出
            System.out.println(result.toString());
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

注意其中为Job提供的两个动态参数,以及在配置文件中的用法。

      pojo类Goods的内容如下:

package com.wanggc.springbatch.sample.xml.pojo;

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * 商品信息类.
 */
public class Goods {
    /** isin号 */
    private String isin;
    /** 数量 */
    private int quantity;
    /** 价格 */
    private double price;
    /** 客户 */
    private String customer;
    /** 购入日期 */
    private Date buyDay;
    /* getter he setter已经删除 */
}

     input.xml文件内容如下:

     处理结果如下(output.xml):

     下次,将和大家一起讨论关于Spring Batch 对固定长内容文件的读写问题。

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值