javax bean 验证不适用于方法参数

javax bean validation not working on method parameters

javax 验证不适用于方法参数。这是一个测试代码,none javax 验证适用于方法参数...

@RequestMapping(value = "/{id}", method = RequestMethod.PUT, params = "action=testAction")
public Test update(
        @Size(min = 1) @RequestBody List<String> ids,
        @Min(3) @PathVariable String name) {
    return doSomething(ids, name);
}

但我有 class 级验证,效果很好...

@RequestMapping(method = RequestMethod.POST)
@ResponseStatus(HttpStatus.CREATED)
public RoleType create (@RequestBody @Validated(FieldType.class) User user) {
    ...
}

@Size(min = 2, max = 10, groups = { FieldType.class }, message = "Invalid user code")
 public String getId() {
    return _id  ;
}

-- 解--

按照已接受的答案执行所有步骤。 另一个添加是 class 级别

上的注释
@Validated
class UserController
{
   @RequestMapping(value = "/{id}", method = RequestMethod.PUT, params ="action=testAction")
   public Test update(@Size(min = 1) @RequestBody List<String> ids,@Min(3) @PathVariable String name) {
    return doSomething(ids, name);
}
}

您需要注册 MethodValidationPostProcessor bean 以启动方法级别验证注解

delegates to a JSR-303 provider for performing method-level validation on annotated methods.

  @Bean
     public MethodValidationPostProcessor methodValidationPostProcessor() {
          return new MethodValidationPostProcessor();
     }

然后,

@RequestMapping(value = "/{id}", method = RequestMethod.PUT)
public Test update(
        @Size(min = 1) @RequestBody List<String> ids,
        @Min(3) @PathVariable("id") String name) {
    return doSomething(ids, name);
}

如果你想处理验证异常

@ExceptionHandler(value = { ConstraintViolationException.class })
 @ResponseStatus(value = HttpStatus.BAD_REQUEST)
 public String handleResourceNotFoundException(ConstraintViolationException e) {
      Set<ConstraintViolation<?>> violations = e.getConstraintViolations();
      StringBuilder strBuilder = new StringBuilder();
      for (ConstraintViolation<?> violation : violations ) {
           strBuilder.append(violation.getMessage() + "\n");
      }
      return strBuilder.toString();
 }