根据DTO对象验证来验证对象

时间:2020-04-18 15:39:17

标签: java spring-boot validation spring-validator

我想在处理DTO CustomerFailedPaymentDto 对象之前,从csv文件中验证我的对象。我使用@Valid,但仍然无法正常工作。

Mycontroller.java

@PostMapping("/proccessFile")
    public String proccessFile(@RequestParam("file") MultipartFile file) {

     // parse CSV file to create a list of `User` objects
        try (Reader reader = new BufferedReader(new InputStreamReader(file.getInputStream()))) {

            // create csv bean reader
             CsvToBean<CustomerFailedPaymentDto> csvToBean = new CsvToBeanBuilder(reader)
                                .withType(CustomerFailedPaymentDto.class)
                                .withIgnoreLeadingWhiteSpace(true)
                                .build();

            // I WANT TO VALIDATE THIS OBJECT                
            List <@Valid CustomerFailedPaymentDto> customerFailedPayment = csvToBean.parse();

            return virtualAccountService.buildFailedQuery(customerFailedPayment);                             

        } catch (Exception ex) {
           return "An error occurred while processing the CSV file.";
        }

    }

CustomerFailedPaymentDto.java

@Data
public class CustomerFailedPaymentDto {
    private Long id;
    @NotEmpty(message = "Please provide a bankPartner")
    private String bankPartner;

    @NotEmpty(message = "Please provide a bankCoreCode")
    private String bankCoreCode;

    @NotEmpty(message = "Please provide a transactionDate")
    private String transactionDate;
}

如何基于DTO类验证确保从csv文件获取的对象有效?

1 个答案:

答案 0 :(得分:2)

需要触发验证,在您的情况下spring不会执行。

使用javax.validation.Validator

首先自动连接验证器

@Autowired
private final Validator validator;

然后针对每个列表项使用验证器进行验证。

Set<ConstraintViolation<CustomerFailedPaymentDto>> violations = validator.validate(perCustomerFailedPayment);
if (!violations.isEmpty()) {
  throw new ConstraintViolationException(new HashSet<ConstraintViolation<?>>(violations));
}