How to validate attributes in Spring Batch

1

I'm working with Spring Batch . In my batch processing, my reader needs to read a .csv file.

When I read the file, I have a class that represents each line, and I would like to know how to validate the input data. I know that Spring uses some tags like @NotNull , @NotEmpty , but I was not able to work with Spring Batch , there are several examples of use of these tag's tags, but together with Spring MVC     

asked by anonymous 31.01.2017 / 14:27

1 answer

0

You can use Bean Validation following the example:

Class with annotations:

public class Cliente {

    @NotNull("O nome é obrigatorio")
    @Size(min = 3, max = 20)
    private String nome;

    @NotNull("O sobre nome é obrigatorio")
    @Size(min = 3, max = 40)
    private String sobrenome;

    // getters e setters

}

Code to validate annotations:

ValidatorFactory factory = Validation.buildDefaultValidatorFactory();
Validator validator = factory.getValidator();
Cliente cliente = new Cliente();
cliente.setNome("Ana");
cliente.setSobrenome("S.");

Set<ConstraintViolation<Cliente>> restricoes = validator.validate(cliente);

if(!restricoes.isEmpty()){
    //EDIT
    trow new MyCustomConstraintViolationException(restricoes);
}

// EDIT Class MyCustomConstraintViolationException:

public class MyCustomConstraintViolationException extends RuntimeException {
    private static final long serialVersionUID = 1L;

    private Set<ConstraintViolation<Cliente>> restricoes

    public MyCustomConstraintViolationException(Set<ConstraintViolation<Cliente>> restricoes) {
        super("");
        this.restricoes = restricoes;
    }

    public Set<ConstraintViolation<Cliente>> getRestricoes(){
        return restricoes;
    }

}
    
31.01.2017 / 16:37