I can't make custom validation working with Spring MVC. I implemented own annotation for parameter and custom validator for it (all is given below), but validation never happens. Any ideas would be really appreciated.
Controller
@Validated
@RestController
public class FooController {
@RequestMapping(value = "/somepath",
method = RequestMethod.GET,
produces = MediaType.APPLICATION_JSON_VALUE)
@ResponseStatus(HttpStatus.OK)
public String get(@CustomParam @RequestParam(String fooParam) {
return "Hello";
}
}
Custom Request Parameter
@Documented
@Constraint(validatedBy = CustomValidator.class)
@Target({ElementType.PARAMETER})
@Retention(RetentionPolicy.RUNTIME)
public @interface CustomParam {
String message() default "Wrong!";
Class<?>[] groups() default {};
Class<? extends Payload>[] payload() default {};
}
Custom Validator
@Component
public class CustomValidator implements ConstraintValidator<CustomParam, String> {
@Override
public void initialize(CustomParam param) {}
@Override
public boolean isValid(String givenParam, ConstraintValidatorContext context) {
// some custom validation is here, never enter this method though
}
}
Seems I got what is wrong here. Because I use Spring Boot, it uses hibernate validator by default. To fix this, I followed this answer and just changed my Spring configuration with adding the beans.
@Bean
public Validator validator() {
return new LocalValidatorFactoryBean();
}
@Bean
public MethodValidationPostProcessor methodValidationPostProcessor() {
MethodValidationPostProcessor methodValidationPostProcessor = new MethodValidationPostProcessor();
methodValidationPostProcessor.setValidator(validator());
return methodValidationPostProcessor;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With