问题
I start job following way:
jobExecution = jobLauncher.run(job, jobParameters);
jobExecution... /// I want to get Map with results here
Also I have following writer:
@Component
public class MyWriter implements ItemWriter<MyBean> {
@Override
public void write(@NonNull List<? extends MyBean> items) throws Exception {
MyResult result = someComponent.doSmth(items);
}
}
}
I want to put result into Map to collect all results within single job execution.
How could I achieve it?
回答1:
You can put the result in the job execution context, something like:
@Component
public class MyWriter implements ItemWriter<MyBean> {
private JobExecution jobExecution;
@BeforeStep
public void beforeStep(StepExecution stepExecution) {
jobExecution = stepExecution.getJobExecution();
}
@Override
public void write(@NonNull List<? extends MyBean> items) throws Exception {
MyResult result = someComponent.doSmth(items);
jobExecution.getExecutionContext().put("result", result); // not sure how you are planning to use a map here
}
}
Then get it from the execution context of the returned job execution:
jobExecution = jobLauncher.run(job, jobParameters);
// I want to get Map with results here
MyResult result = jobExecution.getExecutionContext().get("result");
回答2:
Not sure why and how exactly you want to collect the results in a Map, but if a List (that you could transform into a Map afterwards) would also do, then here's an idea:
Instead of invoking someComponent.doSmth in a custom ItemWriter, I would rather do that in an ItemProcessor's process method (which processes only one item at a time, mind you), return the result, and then let a ListItemWriter receive all the results and store them in a List that you can access via method ListItemWriter.getWrittenItems.
来源:https://stackoverflow.com/questions/58861412/how-to-put-data-to-job-scope-map-inside-the-writer