Spring Batch将文件写入多个目标

我正在编写spring批处理,我正在读取XML数据,处理它,然后将处理器结果作为 map<string,object> 传递给writer并实现CompositeItemWriter . 以下是所需的输出XML .

<Company att1="value">
      <employees>
        <employee></employee>
         <employee></employee>
         <employee></employee>
      <employees>
    </Company>

生成用于编组和解组的JAXB xjc类 . JAXB生成的类如下所示 .

@XmlRootElement(name="Company")
public class Company{
@XmlElements(name="employees" required="true")
}

JAXB员工类

@XmlRootElement(name="employees")
public class Employees
{
@XmlElement(name="Employee")
protected List<Employees> employee;
}

Spring XML配置文件

<batch:job id="reportJob">
<batch:step id="step1">
<batch:tasklet>
<batch:chunk reader="xmlItemReader" 
 writer="compositeItemWriter" processor="filterReportProcessor"
 commit-interval="2">
 </batch:chunk>
 </batch:tasklet>
</batch:step>
</batch:job>



<!-- Filtering process -->
<bean id="filterReportProcessor" class="com.examples.FilterReportProcessor" />

<bean id="xmlItemReader" 
    class="org.springframework.batch.item.xml.StaxEventItemReader">
<property name="fragmentRootElementName" value="record" />
<property name="resource" value="classpath:xml/company.xml" />
<property name="unmarshaller" ref="reportUnmarshaller" />
</bean>

<!-- Read and map values to object, via jaxb2 -->
<bean id="reportUnmarshaller" class="org.springframework.oxm.jaxb.Jaxb2Marshaller">
<property name="classesToBeBound">
<list>
    <value>com.examples.Company</value>
    <value>com.examples.Employees</value>
    <value>com.examples.Employee</value>
</list>
</property>
</bean>

<bean id="compositeItemWriter" class="org.springframework.batch.item.support.CompositeItemWriter">
<property name="delegates"/>
    <list>
       <ref bean="testXMlWriter">
  </list>
</bean>
<bean id="testXMlWriter" class="com.test.example.TestXMLWriter">

处理器和写入器:

public class FilterReportProcessor
    implement ItemProcessor<Employee,Map<String,Object>>{
    public Map<String,Object> process(Employee emplpyee) throws Exception{
    Map<String,Object> evnt = Mapper.crateMapping(emplpyee);
    return event; 
    }

    public class TestXMLWriter implemtes ItemWriter(Map<String,Object>){
    write(List <? extends Map<String, object>> lst){

    Employee e1 = new Employee();
    e1.setxxx(mapelementdata.item());

    Employees employs = new Employees();
    employs.add(e1);
    Comapany c1 = new Company();
    c1.add(employs);

   Marshaller m = context.createMarshaller();
   m.marshal(c1, resource.getFile());
  }

问题:

XML文件覆盖每个固定的提交间隔,显然XML文件在每个提交级别之后创建 . 但我必须将所有 <employee> 对象附加到同一XML文件中 . 如何在每次提交间隔后实现此逻辑以附加 <employee> 对象?

回答(1)

2 years ago

我想你想写同一个文件,在这种情况下,我建议使用FlatFileItemWriter而不是你自己的自定义编写器,并将属性appendAllowed设置为true,如果它已经存在,这将附加到文件 . 移动处理逻辑到您的处理器并使用lineAggregator将多个行批处理以进行写入 .

如果您不想这样做,那么您必须采用更复杂的编码,在WriterListener的beforeWrite方法中打开文件,读取内容然后将其存储在上下文中,然后将其推送到write方法 .