简体   繁体   中英

Get bean validation message from spring batch

I'm using Spring Batch and beanValidationItemProcessor() as defined in the documentation.

@Bean
@StepScope
public BeanValidatingItemProcessor<VendorDTO> beanValidatingItemProcessor() throws Exception {
    BeanValidatingItemProcessor<VendorDTO> beanValidatingItemProcessor = new BeanValidatingItemProcessor<>();
    beanValidatingItemProcessor.setFilter(false);

    return beanValidatingItemProcessor;
}

When a validation occurs a org.springframework.batch.item.validator.ValidationException is thrown and I'm able to see my field error like so.

Field error in object 'item' on field 'peid': rejected value []; codes [Size.item.peid,Size.peid,Size.java.lang.String,Size]; arguments [org.springframework.context.support.DefaultMessageSourceResolvable: codes [item.peid,peid]; arguments []; default message [peid],12,1]; default message [size must be between 1 and 12]

How do I get a simple message object resolving the field id and default message?

I've found I've been able to gain access to the field errors by casting the ValidationException getCause() to BindException where I then have access to the field errors.

@OnSkipInProcess
public void logSkippedEmail(VendorDTO vendorDTO, Throwable t) {
    JobExecution jobExecution = stepExecution.getJobExecution();

    if (t instanceof ValidationException) {
        ValidationException e = (ValidationException) t;

        if(e.getCause() instanceof BindException) {
            BindException bindException = (BindException) e.getCause();

            List<FieldError> fieldErrors = bindException.getFieldErrors();

            for (FieldError fieldError : fieldErrors) {
                BatchValidation batchValidation = new BatchValidation();

                batchValidation.setDataField(fieldError.getField());
                batchValidation.setRejectedValue(String.valueOf(fieldError.getRejectedValue()));
                batchValidation.setValidationMessage(fieldError.getDefaultMessage());
                batchValidation.setJobInstanceId(jobExecution.getJobId());
                batchValidation.setJobName(jobExecution.getJobInstance().getJobName());

                batchValidationRepository.save(batchValidation);
            }
        }

    }

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM