首页 > 解决方案 > 无法在 Java 中对数组的元素执行 Bean 验证

问题描述

我有一个 Spring Boot 应用程序,我需要在其中执行对象验证。

必须验证的对象:

public class MyObject {
   @NotNull
   @Size(min=5)
   @ApiModelProperty(value = "first name", required=true)
   private String firstName;

   //getters and setters for firstName
}

现在在我的控制器中,我有两种方法-

public ResponseEntity<RespObject> getSingleResp(@Valid @RequestBody MyObject myObj) {
//Bean validation works I get a 400 if validation fails, only if it is valid then execution enters this method
}

public ResponseEntity<RespObject[]> getMultiResp(@Valid @RequestBody MyObject[] myObjs) {
//Bean validation does not happen here and starts execution of this method
}

我也尝试@NotNull @NotEmpty在两者之间添加@Valid @RequestBodyMyObject[] myObjs查看是否发生了验证,但它似乎不起作用。

我是否在这里遗漏了一些愚蠢的东西,或者 Bean 验证不适用于数组的各个元素?如果它不起作用,那么是否有解决方法来解决这个问题?

我为 List 找到了一个类似的问题,但那里的解决方案似乎对我不起作用。在 Spring 中验证对象列表

标签: javaspringspring-bootvalidationjavabeans

解决方案


推荐阅读