我正在使用 Spring 批处理进行批处理,在进行批处理之前,我想验证所有作业参数,例如productName, productID, start date, end date, productType
,如果这些作业参数为空或包含错误值,我必须使验证步骤失败并使作业失败。
我已经编写了验证步骤和 Tasklet,在我的 Tasklet 中我打算处理作业参数验证(对所有作业参数进行空检查)。因为我是第一次做 Spring 批处理,所以我想听专家说这是处理工作参数验证的正确地方,或者有没有任何有效的方法来做这件事。如果有人可以帮助我提供您的宝贵建议或示例,那将非常有帮助。
提前感谢您的帮助!谢谢
请在下面找到我的示例代码:
MyJobConfig.java
@Configuration
public class MyJobConfig {
@Autowired
public JobBuilderFactory jobBuilderFactory;
@Autowired
public StepBuilderFactory stepBuilderFactory;
@Bean("myBatchJob")
public Job job(@Qualifier("validateProductJobParam") Step validateProductJobParametersStep) {
Job job = jobBuilderFactory.get("myBatchJob")
.incrementer(new RunIdIncrementer())
.start(validateProductJobParametersStep)
.on("FAILED")
.end()
.from(validateProductJobParametersStep).on("*").to(processProductBatch)
.end()
.build();
return job;
}
@Bean(name = "validateProductJobParam")
public Step validateProductJobParametersStep() {
return stepBuilderFactory.get("validate-product-param")
.tasklet(new JobParamValidateTasklet())
.allowStartIfComplete(true)
.build();
}
}
JobParamValidateTasklet.java
import org.springframework.batch.core.*;
import org.springframework.batch.core.scope.context.ChunkContext;
import org.springframework.batch.core.step.tasklet.Tasklet;
import org.springframework.batch.repeat.RepeatStatus;
import java.util.Map;
public class JobParamValidateTasklet implements Tasklet, StepExecutionListener {
private StepExecution stepExecution;
private JobExecution jobExecution;
private bookean isValidation;
@Override
public void beforeStep(StepExecution stepExecution) {
this.stepExecution = stepExecution;
this.jobExecution = stepExecution.getJobExecution();
}
@Override
public RepeatStatus execute(StepContribution stepContribution, ChunkContext chunkContext) throws Exception {
Map<String,JobParameter> jobMap = jobExecution.getJobParameters().getParameters();
String productName = (String)jobMap.get("PRODUCT_NAME").getValue();
String productId = (String)jobMap.get("PRODUCT_ID").getValue();
String prdouctType = (String)jobMap.get("PRODUCT_TYPE").getValue();
if (productName == null && productId == null && prdouctType == null ) {
isValidation = false;
} else {
isValidation = true;
}
return null;
}
public ExitStatus afterStep(StepExecution stepExecution) {
if(!isValidation)
return ExitStatus.FAILED;
else
return ExitStatus.COMPLETED;
}
}