问题
My service is starting spring batch job. I want to be able to pass some object to the job, each time this object parameter will be different. This object I need to use in my tasklet. I am starting the job by JobLauncher. As far as I googled, I see that JobParameters wont' help me in this case. Also I found that lots of answers are to use JobExecutionContext or whatsoever. But I want to inject parameter object right before job start. Is it posssible?
Service which starts the job
@Service
public class MyServiceImpl implements MyService {
@Autowired
private JobLauncher jobLauncher;
@Autowired
private Job myJob;
@Override
public MyResponse startJob(InputParameter inputObject) {
try {
//Here I want to pass somehow inputObject ot JobExecution
jobLauncher.run(myJob, new JobParameters());
} catch (Exception e) {
return new MyResponse("FAILED")
}
return new MyResponse("OK");
}
}
My Tasklet
@Component
@Scope("step")
public class MyTasklet implements Tasklet{
@Override
public RepeatStatus execute(StepContribution contribution, ChunkContext chunkContext) throws Exception {
InputParameter inputObject = chunkContext.getStepContext().getJobExecutionContext().get("inputObject");
//... the main logic
return RepeatStatus.FINISHED;
}
}
回答1:
Here's what I do to pass params to a Job:
JobParametersBuilder builder = new JobParametersBuilder();
builder.addString("fileName", fileName);
builder.addLong("time", System.currentTimeMillis());
String jobParam = request.getParameter("job");
jobLauncher.run(myJob, builder.toJobParameters());
回答2:
Use the below class to send CustomObject.
public static class CustomJobParameter<T extends Serializable> extends JobParameter {
private T customParam;
public CustomJobParameter(T customParam){
super("");
this.customParam = customParam;
}
public T getValue(){
return customParam;
}
}
===========================
Usage:
Sending parameter:
JobParameters paramJobParameters = new JobParametersBuilder().addParameter("customparam", new CustomJobParameter(myClassReference)).toJobParameters();
Retrieving parameter:
MyClass myclass = (MyClass)jobExecution.getJobParameters().getParameters().get("customparam").getValue();
来源:https://stackoverflow.com/questions/34680189/passing-object-as-parameter-when-starting-spring-batch-job