springspring-bootvalidationspring-validatorspring-validation

How to register custom Spring validator and have automatic dependency injection?


When working with ConstraintValidators, we just need to define the class and constraint and Spring is able to detect the validators and instantiate them automatically, injecting any beans we ask for in the constructor.

How do I add my custom Spring Validators (https://docs.spring.io/spring-framework/docs/current/javadoc-api/org/springframework/validation/Validator.html) in the same manner?


Solution

  • You have to let the controller to know which validator will validate your request. I use following code to find supported validators:

    @ControllerAdvice
    @AllArgsConstructor
    public class ControllerAdvisor {
    
        private final List<Validator> validators;
    
        @InitBinder
        public void initBinder(@NonNull final WebDataBinder binder) {
            final Object request= binder.getTarget();
            if (request== null) {
                return;
            }
            this.validators.stream()
                .filter(validator -> validator.supports(request.getClass()))
                .forEach(binder::addValidators);
        }
    
    }
    
    

    Note that you have to create those validators as beans. Therefore, you should annotate those validators with @Component. Hope this help you.