我们有一个 Spring Batch 作业,可以从文件中提取动态的收件人列表。我们希望添加一个额外的收件人来充当质量控制。我考虑添加一个新的 tasklet,它只是吐出此记录并将其传递给真正的读者。我在这里阅读了一些问题、其他地方的文章以及有关在 Spring Batch 步骤之间传输数据的文档,但我不确定这是实现此目的的最简单或最好的方法。
喜欢 official documentation使用监听器,this article使用 Autowiring 组件和不同的监听器,以及 this question and answers .
如果我确实设置了生成器微线程并将其数据传递给读取器,我将如何将其插入读取器的实际记录中?
我们正在使用的代码的一些片段 - 它纯粹是注释驱动的,任何地方都没有 XML 配置设置。
步骤生成器
public Step loadRecipients() {
return stepBuilderFactory.get("loadRecipients").<Recipient, Recipient>chunk(chunkSize)
.reader(recipientsItemReader)
.processor(recipientsItemProcessor)
.writer(recipientsWriter)
.taskExecutor(taskExecutor)
.throttleLimit(1)
.build();
}
阅读器配置
@StepScope
public FlatFileItemReader<Recipient> recipientItemReader() {
FlatFileItemReader<Recipient> itemReader = new FilePrefixItemReader<>(
"theFilePath",
staticResourceLoader(),
FunctionUtils.propagateExceptions((org.springframework.core.io.Resource resource) -> new GZIPInputStream(resource.getInputStream()))
);
userCategoryItemReader.setLineMapper(userCategoriesDefaultLineMapper);
return userCategoryItemReader;
}
我应该用一些时髦的包装器将我的额外记录骗到资源输入流中吗?我可以使用其他 Spring 魔法来添加静态记录吗?
最佳答案
包装/扩展 Writer 并在其中添加静态项,粗略源代码:
public class AddStaticItemWriter implements ItemWriter<String> {
@Override
public void write(final List<? extends String> items) throws Exception {
// check some funky condition
if (addStaticItem) {
items.add(STATIC_ITEM);
}
// business code
// or delegate to underlying writer
}
}
一些提示(优点、缺点):
- 添加的项目对于 Spring Batch 来说是未知的,可能会导致回滚场景中出现一些奇怪的事情(跳过,重试)
- 像上面一样,您可以包装阅读器并在其中添加项目
关于java - 我可以将单个静态项目注入(inject) Spring Batch 项目读取器吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36324675/