4

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.

Zhozhe
  • 403
  • 2
  • 5
  • 14

1 Answers1

0

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();
    }
}

rogeriolino
  • 1,095
  • 11
  • 21
  • Related question: https://stackoverflow.com/questions/73649311/spring-cloud-stream-validation-functional-approach/73737777 – rogeriolino Sep 15 '22 at 21:50