Spring Cloud Stream and Hibernate Validator

Viewed 211

Recently, I've been playing with the last version of spring cloud Stream ( using its functional programming style). Although I have read the whole documentation, I could not understand how could I use hibernate Validator in my function. I've read the source code and I have understood that the only resolver that could validate the payload is SmartPayloadArgumentResolver but it's been never selected because the parameter type is always of type message. So, I was wondering how could I use the validator in my function? here is my listener implementation.

@Component
public class SampleListener implements Function<Person, String>{

   @Override
   public String apply(@Valid Person person) {
       return person.getName().toUpperCase();
   }
}

In my example person's name has been annotated with @NotBlank but the problem is that I would get NullPointerException if instead of hibernate validator exception.

1 Answers

You must do it manually, injecting a Validator instance into your component, then calling validator.validate(person):

@Component
public class SampleListener implements Function<Person, String> {

    private final Validator validator; 

    @Override
    public String apply(Person person) {
        Set<ConstraintViolation<Person>> constraints = validator.validate(person);
        if (!constraints.isEmpty()) {
            // handle validation errors
        }
        return person.getName().toUpperCase();
    }
}

Related