Search code examples
spring-cloud-stream

Spring Cloud Stream validation (functional approach)


There is an old question how to use @Valid annotation with spring-cloud-stream library, there is even documentation how to do it in docs but in October 6 2020 @StreamListener approach was officially deprecated and example removed.

Old way:

@StreamListener(Processor.INPUT)
@SendTo(Processor.OUTPUT)
public VoteResult handle(@Valid Vote vote) {
  return votingService.record(vote);
}

New way:

public Function<Vote, VoteResult> handle() {
  return vote -> votingService.record(vote);
}

My question is, how migrate this functionality using new functional model?


Solution

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

    private final Validator validator;
    
    public Function<Vote, VoteResult> handle() {
      return vote -> {
        Set<ConstraintViolation<Vote>> constraints = validator.validate(vote);
        if (!constraints.isEmpty()) {
          // handle validation errors
        }
        votingService.record(vote);
      }
    }
    

    Same as Spring Cloud Stream and Hibernate Validator