springboot~@Valid注解對嵌(qian)套類型(xing)的(de)校驗
@Valid注解可以(yi)實現(xian)數據(ju)的(de)驗(yan)證,你可以(yi)定義實體(ti),在(zai)實體(ti)的(de)屬性上添加校驗(yan)規則(ze),而在(zai)API接收(shou)數據(ju)時(shi)添加@valid關鍵字,這時(shi)你的(de)實體(ti)將會(hui)開啟一個(ge)校驗(yan)的(de)功能(neng),具體(ti)的(de)代碼如下,是最基本的(de)應用:
實體:
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接口(kou):
@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());{}
上面代碼中,我們為(wei)請求(qiu)體Request<DepartmentDto>添加了校驗,在測試時(shi),如果你的DepartmnetDto.name為(wei)空字符(fu)(fu)時(shi),當出現400的異常,麗時(shi)異常消息是(shi)『部(bu)門名稱(cheng)不能為(wei)空』,這(zhe)對于我們來說(shuo)是(shi)沒有問題的,也是(shi)符(fu)(fu)合我們要求(qiu)的,下面看(kan)另一個場(chang)景。
需要驗證的實體是另一個實休的屬性
這種方式我們也需要會看到,一個大對象,如被封裝的其它小對象組成,比如部門下面有員工,這時如果需要驗證員工的有效性,需要如何實現呢?如果我們不修改源代碼,執行結果是否定的,它并不會校驗員工這個對象(xiang),而只針對第一(yi)層(ceng)對象(xiang)的(de)屬性。
我們將實體的員工屬(shu)性(xing)添加(jia)上@Valid即(ji)可實現(xian)對這個屬(shu)性(xing)的校(xiao)驗(yan)
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<>(); }
下面看(kan)一下驗證結果,我(wo)們(men)的400錯(cuo)誤就可(ke)以在單元測(ce)試下面正常輸(shu)出了(le)!
@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的話,由于用戶名為空(kong),所以會(hui)出(chu)現錯誤提示
api.post() .uri("/v1/12345/2018-03") .body(BodyInserters.fromObject(request)) .exchange() .expectStatus().isOk();

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

感謝各位閱讀!
今天主要介紹 @Valid在項(xiang)目中的使用!