How to get JobParameter and JobExecutionContext in the ItemWriter?

会有一股神秘感。 提交于 2019-12-03 15:20:17

问题


I want to retrieve JobParameter and JobExecutionContext object in my ItemWriter class. How to proceed?

I tried implementing StepExecutionListener through which I am just calling the parent class methods. But it is not succeeding.

Thanks in advance.


回答1:


Implementing StepExecutionListener is one way. In fact that's the only way in Spring Batch 1.x.

Starting from Spring Batch 2, you have another choice: You can inject whatever entries in Job Parameters and Job Execution Context to your item writer. Make your item writer with step scope, then make use of expression like #{jobParameters['theKeyYouWant']} or #{jobExecutionContext['someOtherKey']} for value injecting to you item writer.




回答2:


Use the @BeforeStep annotation to call a method before step processing.

//From the StepExecution get the current running JobExecution object.
public class MyDataProcessor implements ItemProcessor<MyDataRow, MyDataRow> {
    private JobExecution jobExecution;

    @BeforeStep
    public void beforeStep(StepExecution stepExecution) {
        jobExecution = stepExecution.getJobExecution();
    }
}



回答3:


To add to Adrian Shum's answer, if you want to avoid each job parameter to be injected as a class property, you can directly inject the Map of JobParameters as follows:

@Value("#{jobParameters}")
private Map<String, JobParameter> jobParameters;



回答4:


If you are using Spring Configuration file, you can access the StepExecution object with:

<bean id="aaaReader" class="com.AAAReader" scope="step">
    <property name="stepExecution" value="#{stepExecution}" />
</bean>

In AAAReader class you need to create the proper field and a setter:

private StepExecution stepExecution;

public void setStepExecution(final StepExecution stepExecution) {
    this.stepExecution = stepExecution;
}

Same for Processor and Writer classes.



来源:https://stackoverflow.com/questions/14949985/how-to-get-jobparameter-and-jobexecutioncontext-in-the-itemwriter

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