Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Custom validation for RequestParam doesn't work with Spring MVC

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
    }

}
like image 553
Maksim Avatar asked Oct 19 '22 11:10

Maksim


1 Answers

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;
}
like image 125
Maksim Avatar answered Oct 30 '22 16:10

Maksim