How to put data to job scope Map inside the writer?

允我心安 提交于 2019-12-11 16:55:45

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!