When working with ConstraintValidator
s, 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 Validator
s (https://docs.spring.io/spring-framework/docs/current/javadoc-api/org/springframework/validation/Validator.html) in the same manner?
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.