RequestParam的自定义验证不适用于Spring MVC

时间:2016-04-24 12:44:21

标签: java spring validation spring-mvc

我无法使用Spring MVC进行自定义验证。我为它实现了自己的参数和自定义验证器注释(所有都在下面给出),但验证永远不会发生。任何想法都会非常感激。

控制器

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

}

自定义请求参数

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

}

自定义验证器

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

}

1 个答案:

答案 0 :(得分:1)

似乎我在这里弄错了。因为我使用Spring Boot,所以它默认使用hibernate验证器。为了解决这个问题,我按照this回答,只是添加了bean来改变我的Spring配置。

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

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