Search code examples
javaspring-boothibernate-validatorspring-validator

How to enable bean validator - Spring boot


I am consuming data from Kafka into a bean class which has validation to make sure that the message which I am reading is having valid data.

I have added annotations to the bean class, like @NotNull & @Pattern but that is not getting applied.

public class Class {
    @NotNull
    private String field1;

    @Pattern(regexp = "^Open$|^Active$|^Overdue$|^Inactive$")
    private String field2;
}

How can I make sure bean validation is applied, I have use @RequestBody @Valid earlier while creating REST services but not sure how to apply in this scenario.


Solution

  • Programmatic Validation :

    Some frameworks – such as Spring – have simple ways of triggering the validation process by just using annotations. This is mainly so that we don’t have to interact with the programmatic validation API.

    Let’s now go the manual route and set things up programmatically:

    ValidatorFactory factory = Validation.buildDefaultValidatorFactory();
    Validator validator = factory.getValidator();
    

    To validate a bean, we must first have a Validator object, which is constructed using a ValidatorFactory.

    We’re now going to set up this invalid user – with a null name value:

    User user = new User();
    user.setWorking(true);
    user.setAboutMe("Its all about me!");
    user.setAge(50);
    

    Now that we have a Validator, we can validate our bean by passing it to the validate method. Any violations of the constraints defined in the User object will be returned as a Set.

    Set<ConstraintViolation<User>> violations = validator.validate(user);
    

    By iterating over the violations, we can get all the violation messages by using the getMessage method.

    for (ConstraintViolation<User> violation : violations) {
    log.error(violation.getMessage()); 
     }