![](/img/trans.png)
[英]How to read multiple CSV files in Spring Batch to merge the data for processing?
[英]How to access read raw data in a spring batch job (xml or csv)
我有不同的導入作業來將數據導入我們的系統。 由於數據來自不同的生產者,我有時會有 csv 數據或不同格式的 xml。 這些導入類型中的每一種都有自己的 spring 批處理作業和自己的配置(不同的讀取器、不同的處理器但都是相同的寫入器)。
我現在的任務是,我還需要系統中的“原始數據”,而不僅僅是轉換后的對象。 因此,對於 csv 導入,我想訪問構建一個實體的原始行。 在 XML 中,我希望原始元素作為字符串。 因此,編寫器應該擴展為將我轉換的對象 DTO 加上一個帶有讀取的原始數據的附加字符串。
我只是不知道如何使用 Spring Batch 訪問原始數據。 我嘗試了幾種方法來使用 ItemReadListener#beforeRead 或 afterRead 進入處理線,但我無法訪問文件中的原始數據。
關於我可以進一步研究的任何想法? 或有關如何獲取原始數據 + 轉換后的 dto 對象的提示?
您不必將數據映射到域對象,您的項目可以是String
類型。
對於平面文件,您可以使用PassThroughLineMapper ,它將逐字提供原始行:
@Bean
public FlatFileItemReader<String> itemReader() {
return new FlatFileItemReaderBuilder<String>()
.name("rawDataReader")
.resource(new FileSystemResource("/absolute/path/to/your/flat/file"))
.lineMapper(new PassThroughLineMapper())
.build();
}
對於 XML 文件,您可以對StaxEventItemReader<String>
使用相同的方法。 但是,Spring Batch 將解組過程委托給org.springframework.oxm.Marshaller
,因此根據您使用的 XML 實現,您需要相應地配置解組器:
@Bean
public StaxEventItemReader<String> itemReader() {
Marshaller marshaller = .. // create or inject marshaller
// configure marshaller to unmarshal raw strings
return new StaxEventItemReaderBuilder<String>()
.name("rawXmlDataReader")
.resource(new FileSystemResource("/absolute/path/to/your/xml/file"))
.addFragmentRootElements("yourTagName")
.unmarshaller(marshaller)
.build();
}
對於 Jaxb,這可能會有所幫助: JAXB 按原樣使用 String
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.