我正在旧系统上使用新的批处理过程。我们由于不使用Spring Boot而受到限制,我们的Spring Batch版本是3.0.8。
要求如下:
我正在使用CompositeItemWriter将上面的两个编写器添加为委托:
@Bean
public CompositeItemWriter<Report> compositeItemWriter() throws Exception {
CompositeItemWriter<Report> compositeItemWriter = new CompositeItemWriter<>();
List<ItemWriter<? super Report>> writerDelegates = new ArrayList<>();
writerDelegates.add(reportXMLWriter());
writerDelegates.add(reportDatabaseWriter());
compositeItemWriter.setDelegates(writerDelegates);
compositeItemWriter.afterPropertiesSet();
return compositeItemWriter;
}
reportXMLWriter是一个具有自己的委托的MultiResourceItemWriter:
@Bean
public MultiResourceItemWriter<Report> reportXMLWriter() {
MultiResourceItemWriter<Report> writer = new MultiResourceItemWriter<>();
writer.setResource(new FileSystemResource(new File(getDestination())));
writer.setResourceSuffixCreator(new XMLSuffixCreator());
writer.setDelegate(reportWriterDelegate());
writer.setItemCountLimitPerResource(this.chunkSize);
return writer;
}
reportWriterDelegate和reportDatabaseWriter都实现ResourceAwareItemWriterItemStream:
public class ReportItemWriterDelegate implements ResourceAwareItemWriterItemStream<Report> {
@Override
public void write(List<? extends Report> items) throws Exception {
// writes XML files for the current chunk
}
...
}
public class ReportDatabaseWriter implements ResourceAwareItemWriterItemStream<Report> {
@Override
public void write(List<? extends Report> items) throws Exception {
// writes status info back to the DB
...
}
}
到目前为止很好-现在是问题:
我需要能够将文件名(在每个块的开头在ReportWriterDelegate资源中设置)写回到ReportDatabaseWriter中的数据库。
我尝试将CompositeItemWriter(及其委托)设置为MultiResourceItemWriter中的委托。这将使xml和数据库编写器在块的开头都设置了资源。设置起来似乎很简单,但是现在我使用以下配置代码在复合项目编写器中得到ClassCastException:
@Bean
public ResourceAwareItemWriterItemStream<? super Report> compositeItemWriter() throws Exception{
CompositeItemWriter<Report> compositeItemWriter = new CompositeItemWriter<>();
List<ItemWriter<? super Report>> writerDelegates = new ArrayList<>();
writerDelegates.add(reportWriterDelegate());
writerDelegates.add(reportDatabaseWriter());
compositeItemWriter.setDelegates(writerDelegates);
compositeItemWriter.afterPropertiesSet();
return (ResourceAwareItemWriterItemStream<? super InspectionReport>) compositeItemWriter;
}
运行时错误为:
Caused by: java.lang.ClassCastException: org.springframework.batch.item.support.CompositeItemWriter cannot be cast to org.springframework.batch.item.file.ResourceAwareItemWriterItemStream
也不完全确定如何将当前资源通过CompositeItemWriter传递给其每个委托-也许扩展CompositeItemWriter以使其成为ResourceAware?
我应该将MultiResourceItemWriter保留为CompositeItemWriter委托之一吗?如果是这样,如何使XML编写器中的资源文件名在ReportDatabaseWriter中可用?
如果您已读过本文,感谢您的支持。我希望对此发表任何评论。