2016-04-24 69 views
2

我無法使用Spring MVC進行自定義驗證。我爲它的參數和自定義驗證器實現了自己的註釋(全部在下面給出),但驗證從不發生。任何想法將非常感激。RequestParam的自定義驗證不適用於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 
    } 

} 

回答

0

似乎我在這裏遇到了什麼問題。因爲我使用Spring Boot,所以默認使用hibernate驗證器。爲了解決這個問題,我遵循this的答案,只是改變了我的Spring配置,添加了bean。

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

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