Hibernate 验证器 @NotEmpty 不工作 Spring Boot 和 Jackson

Pra*_*r D 2 spring-mvc hibernate-validator jackson spring-restcontroller

我有以下类,其中包含带有 @NotEmpty 注释的 errorRequests。

public class ErrorsRequests implements Serializable {


  private static final long serialVersionUID = -727308651190295062L;

  private String applicationName;

  @NotEmpty
  @Valid
  @JsonProperty("errors")
  private List<ErrorsRequest> errorRequests;
Run Code Online (Sandbox Code Playgroud)

我的控制器如下所示:

 @Autowired
  @Qualifier("errorStreamValidator")
  private Validator errorStreamValidator;

  @RequestMapping(method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_VALUE,
      consumes = MediaType.APPLICATION_JSON_VALUE)
  public ResponseEntity<Void> errorReporting(@NotNull @PathVariable String applicationName,
      @Valid @NotNull @RequestBody ErrorsRequests errorsRequests, BindingResult results) {
Run Code Online (Sandbox Code Playgroud)

我的类路径中有所需的休眠验证器类。

当我输入以下 JSON 时:

{
"errorss": [ 
  ]
}
Run Code Online (Sandbox Code Playgroud)

@NotEmpty 验证根本没有启动。Hibernate 验证仅在 json 中包含错误元素时才有效,如下所示

 {
    "errors": [ 
      ]
    }
Run Code Online (Sandbox Code Playgroud)

我可以让第一个案例也起作用吗?

Iam*_*DOM 5

您以错误的方式使用注释,并且您的控制器也缺少注释。

您应该使用 @Validated 注释您的控制器:

@Validated
@RestController
@RequestMapping("/mycontroller")
public class MyController { ... }
Run Code Online (Sandbox Code Playgroud)

在模型类中,您需要像这样放置注释:

@NotEmpty
private List<@Valid Foo> foo;
Run Code Online (Sandbox Code Playgroud)

@Valid 注释将检查列表中的项目是否也有效。