简体   繁体   中英

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
    }

}

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;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM