me1*_*111 1 java spring spring-batch
我的服务正在启动春季批处理作业。我希望能够将一些对象传递给作业,每次这个对象参数都会不同。我需要在我的 tasklet 中使用这个对象。我正在通过 JobLauncher 开始工作。就我用谷歌搜索而言,我发现 JobParameters 在这种情况下不会帮助我。我还发现很多答案都是使用 JobExecutionContext 或其他任何东西。但我想在工作开始之前注入参数对象。有可能吗?
启动工作的服务
@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");
}
}
Run Code Online (Sandbox Code Playgroud)
我的任务
@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;
}
}
Run Code Online (Sandbox Code Playgroud)
使用以下类发送 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;
}
}
Run Code Online (Sandbox Code Playgroud)
============================
用法:
发送参数:
JobParameters paramJobParameters = new JobParametersBuilder().addParameter("customparam", new CustomJobParameter(myClassReference)).toJobParameters();
Run Code Online (Sandbox Code Playgroud)
检索参数:
MyClass myclass = (MyClass)jobExecution.getJobParameters().getParameters().get("customparam").getValue();
Run Code Online (Sandbox Code Playgroud)