我正在使用spring batch tasklets和opencsv来处理一些csv文件。在步骤1中将文件读入内存之后,在步骤2中,我希望执行一些验证。我不确定设置验证的正确方法是什么。我使用了下面的代码。
public class PrimaryCareValidation implements Tasklet, StepExecutionListener {
private final Logger logger = LoggerFactory.getLogger(PrimaryCareProcessor.class);
private List<PrimaryCareDTO> batch;
@Autowired
private Validator validator;
@Override
public void beforeStep(StepExecution stepExecution) {
logger.info("PrimaryCare validation initialized.");
ExecutionContext executionContext = stepExecution
.getJobExecution()
.getExecutionContext();
this.batch = (List<PrimaryCareDTO>) executionContext.get("PrimaryCareDTO");
}
@Override
public ExitStatus afterStep(StepExecution stepExecution) {
logger.info("PrimaryCare validation ended.");
return ExitStatus.COMPLETED; }
@Override
public RepeatStatus execute(StepContribution contribution, ChunkContext chunkContext) throws Exception {
logger.info("PrimaryCare execute.");
for (PrimaryCareDTO pcDTO : batch) {
DataBinder binder = new DataBinder(pcDTO);
Set<ConstraintViolation<PrimaryCareDTO>> violations = validator.validate(pcDTO);
for (ConstraintViolation<PrimaryCareDTO> violation : violations)
{
String propertyPath = violation.getPropertyPath().toString();
String message = violation.getMessage();
result.addError(new FieldError("employee",propertyPath,
"Invalid "+ propertyPath + "(" + message + ")"));
}
}
return RepeatStatus.FINISHED; }
}验证整个DAO列表并将消息添加到消息对象以便稍后返回到步骤3的最佳方法是什么?
发布于 2018-09-11 05:09:27
我有过非常类似的案例,并且用于这个vavr库。它包含有用的Validation对象,该对象可以保存成功的值-在您的情况下是DTO,或者在失败的情况下-一些消息。然后有一些内置的方法可以帮助你将它们压缩到一个单独的聚合Validation中。
还请注意@Mahmoud在评论中提到的内容。最好使用读取器-写入器-处理器,在这种情况下,它将留下较小的内存占用,并且可以扩展。
现在,您有一个大文件的风险,这将不适合您的应用程序内存。
您的DTO对象也是如此。它们将保留在内存中,除非微线程退出。这是OutOfMemoryException的风险
https://stackoverflow.com/questions/52264428
复制相似问题