springboot~@Valid注解對嵌套類型的校驗


@Valid注解可以實現數據的驗證,你可以定義實體,在實體的屬性上添加校驗規則,而在API接收數據時添加@valid關鍵字,這時你的實體將會開啟一個校驗的功能,具體的代碼如下,是最基本的應用:

實體:

public class DepartmentDto {

  @ApiModelProperty("id")
  private String id;

  @ApiModelProperty("上級Id")
  private String parentId;

  @ApiModelProperty("編號")
  @NotBlank(message = "部門編號不能為空。")
  private String code;

  @ApiModelProperty("名稱")
  @NotBlank(message = "部門名稱不能為空。")
  private String name;
 @ApiModelProperty("員工集合")
@Builder.Default
private List<Employee> employees = new ArrayList<>();
}

Restful接口:

  @PostMapping()
  public Response<ClientAccount> initialAccount(
      @ApiParam("客戶編號") @PathVariable String code,
      @ApiParam("賬期") @PathVariable YearMonth accountPeriod,
      @ApiParam("請求體") @Valid @RequestBody Request<DepartmentDto> request) {
    ClientAccount result = clientAccountService.initialAccount(
        code,
        accountPeriod,
        request.getOperator(),
        request.getBody());{}

上面代碼中,我們為請求體Request<DepartmentDto>添加了校驗,在測試時,如果你的DepartmnetDto.name為空字符時,當出現400的異常,麗時異常消息是『部門名稱不能為空』,這對於我們來說是沒有問題的,也是符合我們要求的,下面看另一個場景。

需要驗證的實體是另一個實休的屬性

這種方式我們也需要會看到,一個大對象,如被封裝的其它小對象組成,比如部門下面有員工,這時如果需要驗證員工的有效性,需要如何實現呢?如果我們不修改源代碼,執行結果是否定的,它並不會校驗員工這個對象,而只針對第一層對象的屬性

我們將實體的員工屬性添加上@Valid即可實現對這個屬性的校驗

public class DepartmentDto {

  @ApiModelProperty("id")
  private String id;

  @ApiModelProperty("上級Id")
  private String parentId;

  @ApiModelProperty("編號")
  @NotBlank(message = "部門編號不能為空。")
  private String code;

  @ApiModelProperty("名稱")
  @NotBlank(message = "部門名稱不能為空。")
  private String name;

 @Valid
 @ApiModelProperty("員工集合")
 @Builder.Default
 private List<Employee> employees = new ArrayList<>();
}

下面看一下驗證結果,我們的400錯誤就可以在單元測試下面正常輸出了!

 @Test
  public void initialAccount_employee_name_empty() {
    List<Employee> employees = new ArrayList<>();
    employees.add(Employee.builder()
        .name("")
        .email("zzl@sina.com")
        .idNumber("110111198203182012")
        .build());
    List<DepartmentDto> departments = new ArrayList<>();
    departments.add(DepartmentDto.builder()
        .name("部門")
        .description("技術部")
        .salaryType(SalaryType.ResearchAndDevelopmentCosts)
        .employees(employees)
        .build());
    ClientAccountDto clientAccountDto = ClientAccountDto.builder()
        .name("客戶")
        .departments(departments)
        .build();
    Request<ClientAccountDto> request = buildRequest(clientAccountDto);
    api.post()
        .uri("/v1/12345/2018-03")
        .body(BodyInserters.fromObject(request))
        .exchange()
        .expectStatus().isEqualTo(400)
        .expectBody()
        .jsonPath("$.errors[0].message").isEqualTo("姓名不能為空");
  }

結果如下,測試通過

如果是測試它是IsOk的話,由於用戶名為空,所以會出現錯誤提示

 api.post()
        .uri("/v1/12345/2018-03")
        .body(BodyInserters.fromObject(request))
        .exchange()
        .expectStatus().isOk();

可以看一下結果的提示信息

感謝各位閱讀!

今天主要介紹 @Valid在項目中的使用!

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM