Dependency Injection in JSR-303 Constraint Validator with Spring fails

I have fought the same problem in Spring Boot environment and I found out that Hibernate internal implementation got in instead of the configured Spring’s one. When the application started, debugger caught a line with the Spring’s factory but later in runtime there was Hibernate’s one. After some debugging, I came to the conclusion that MethodValidationPostProcessor got the internal one. Therefore I configured it as follows:

@Bean
public Validator validator() {
    return new LocalValidatorFactoryBean();
}

@Bean
public MethodValidationPostProcessor methodValidationPostProcessor(Validator validator) {
    MethodValidationPostProcessor methodValidationPostProcessor = new MethodValidationPostProcessor();
    methodValidationPostProcessor.setValidator(validator);
    return methodValidationPostProcessor;
}

Note the setter for validator – it did the job.

Leave a Comment