我想在步骤中的读取器中设置的写入器中获取数据。我通过http://docs.spring.io/spring-batch/trunk/reference/html/patterns.html#passingDataToFutureSteps了解ExecutionContexts(步骤和工作)以及ExecutionContextPromotionListener
问题是在Writer中,我正在检索'npag'的空值。
ItemWriter上的行:
LOG.info("INSIDE WRITE, NPAG: " + nPag);
我正在做一些变通办法,没有运气,正在寻找其他similar questions的答案...有什么帮助吗?谢谢!
这是我的代码:
读者
@Component
public class LCItemReader implements ItemReader<String> {
private StepExecution stepExecution;
private int nPag = 1;
@Override
public String read() throws CustomItemReaderException {
ExecutionContext stepContext = this.stepExecution.getExecutionContext();
stepContext.put("npag", nPag);
nPag++;
return "content";
}
@BeforeStep
public void saveStepExecution(StepExecution stepExecution) {
this.stepExecution = stepExecution;
}
}
作家
@Component
@StepScope
public class LCItemWriter implements ItemWriter<String> {
private String nPag;
@Override
public void write(List<? extends String> continguts) throws Exception {
try {
LOG.info("INSIDE WRITE, NPAG: " + nPag);
} catch (Throwable ex) {
LOG.error("Error: " + ex.getMessage());
}
}
@BeforeStep
public void retrieveInterstepData(StepExecution stepExecution) {
JobExecution jobExecution = stepExecution.getJobExecution();
ExecutionContext jobContext = jobExecution.getExecutionContext();
this.nPag = jobContext.get("npag").toString();
}
}
作业/步骤批处理配置
@Bean
public Job lCJob() {
return jobs.get("lCJob")
.listener(jobListener)
.start(lCStep())
.build();
}
@Bean
public Step lCStep() {
return steps.get("lCStep")
.<String, String>chunk(1)
.reader(lCItemReader)
.processor(lCProcessor)
.writer(lCItemWriter)
.listener(promotionListener())
.build();
}
李斯特
@Bean
public ExecutionContextPromotionListener promotionListener() {
ExecutionContextPromotionListener executionContextPromotionListener = new ExecutionContextPromotionListener();
executionContextPromotionListener.setKeys(new String[]{"npag"});
return executionContextPromotionListener;
}
最佳答案
ExecutionContextPromotionListener专门指出它在步骤的末尾起作用,因此将在编写者执行之后。因此,我认为您所期望的升迁不会在您认为有升空时发生。
如果我是您,那么我将在步骤上下文中进行设置,如果需要在单个步骤中使用该值,则可以从步骤中获取它。否则,我将其设置为工作上下文。
另一个方面是@BeforeStep。这标志着一种在步骤上下文存在之前执行的方法。在阅读器中设置nPag值的方式将是在该步骤开始执行之后。