6.7.2 StaxEventItemWriter

输出与输入相对应. StaxEventItemWriter 需要 1个 Resource, 1个 marshaller 以及 1个 rootTagName. Java对象传递给marshaller(通常是标准的Spring OXM marshaller), marshaller 使用自定义的事件writer写入Resource, 并过滤由OXM工具为每条 fragment 产生的 StartDocument 和 EndDocument事件。我们用 MarshallingEventWriterSerializer 示例来显示这一点。Spring配置如下所示:

  1. <bean id="itemWriter" class="org.springframework.batch.item.xml.StaxEventItemWriter">
  2. <property name="resource" ref="outputResource" />
  3. <property name="marshaller" ref="customerCreditMarshaller" />
  4. <property name="rootTagName" value="customers" />
  5. <property name="overwriteOutput" value="true" />
  6. </bean>

上面配置了3个必需的属性,以及1个可选属性 overwriteOutput = true, (本章前面提到过) 用来指定一个已存在的文件是否可以被覆盖。应该注意的是, writer 使用的 marshaller 和前面讲的 reading 示例中是完全相同的:

  1. <bean id="customerCreditMarshaller"
  2. class="org.springframework.oxm.xstream.XStreamMarshaller">
  3. <property name="aliases">
  4. <util:map id="aliases">
  5. <entry key="customer"
  6. value="org.springframework.batch.sample.domain.CustomerCredit" />
  7. <entry key="credit" value="java.math.BigDecimal" />
  8. <entry key="name" value="java.lang.String" />
  9. </util:map>
  10. </property>
  11. </bean>

我们用一段Java代码来总结所讨论的知识点, 并演示如何通过代码手动设置所需的属性:

  1. StaxEventItemWriter staxItemWriter = new StaxEventItemWriter()
  2. FileSystemResource resource = new FileSystemResource("data/outputFile.xml")
  3. Map aliases = new HashMap();
  4. aliases.put("customer","org.springframework.batch.sample.domain.CustomerCredit");
  5. aliases.put("credit","java.math.BigDecimal");
  6. aliases.put("name","java.lang.String");
  7. Marshaller marshaller = new XStreamMarshaller();
  8. marshaller.setAliases(aliases);
  9. staxItemWriter.setResource(resource);
  10. staxItemWriter.setMarshaller(marshaller);
  11. staxItemWriter.setRootTagName("trades");
  12. staxItemWriter.setOverwriteOutput(true);
  13. ExecutionContext executionContext = new ExecutionContext();
  14. staxItemWriter.open(executionContext);
  15. CustomerCredit Credit = new CustomerCredit();
  16. trade.setPrice(11.39);
  17. credit.setName("Customer1");
  18. staxItemWriter.write(trade);