您好,欢迎来到年旅网。
搜索
您的当前位置:首页springboot@Valid注解对嵌套类型的校验功能

springboot@Valid注解对嵌套类型的校验功能

来源:年旅网
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 employees = new ArrayList<>();}

Restful接⼝:

@PostMapping()

public Response initialAccount(

@ApiParam(\"客户编号\") @PathVariable String code,

@ApiParam(\"账期\") @PathVariable YearMonth accountPeriod,

@ApiParam(\"请求体\") @Valid @RequestBody Request request) { ClientAccount result = clientAccountService.initialAccount( code,

accountPeriod,

request.getOperator(), request.getBody());{}

上⾯代码中,我们为请求体Request添加了校验,在测试时,如果你的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 employees = new ArrayList<>();}

下⾯看⼀下验证结果,我们的400错误就可以在单元测试下⾯正常输出了!

@Test

public void initialAccount_employee_name_empty() { List employees = new ArrayList<>(); employees.add(Employee.builder() .name(\"\")

.email(\"zzl@sina.com\")

.idNumber(\"110111198203182012\") .build());

List departments = new ArrayList<>(); departments.add(DepartmentDto.builder() .name(\"部门\")

.description(\"技术部\")

.salaryType(SalaryType.ResearchAndDevelopmentCosts) .employees(employees) .build());

ClientAccountDto clientAccountDto = ClientAccountDto.builder() .name(\"客户\")

.departments(departments) .build();

Request 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();

可以看⼀下结果的提⽰信息

总结

以上所述是⼩编给⼤家介绍的springboot @Valid注解对嵌套类型的校验,希望对⼤家有所帮助,如果⼤家有任何疑问请给我留⾔,⼩编会及时回复⼤家的。在此也⾮常感谢⼤家对⽹站的⽀持!

因篇幅问题不能全部显示,请点此查看更多更全内容

Copyright © 2019- oldu.cn 版权所有 浙ICP备2024123271号-1

违法及侵权请联系:TEL:199 1889 7713 E-MAIL:2724546146@qq.com

本站由北京市万商天勤律师事务所王兴未律师提供法律服务