在实体类的对应属性上添加 @NotBlank 注解,可以实现对空置的限制。除了 @NotBlank 外,还有 @NotNull 和 @NotEmpty ,它们的区别如下所示:
1.String name = null;
@NotNull: false
@NotEmpty:false
@NotBlank:false
2.String name = "";
@NotNull:true
@NotEmpty: false
@NotBlank: false
3.String name = " ";
@NotNull: true
@NotEmpty: true
@NotBlank: false
4.String name = "Great answer!";
@NotNull: true
@NotEmpty:true
@NotBlank:true
需要注意的是 @NotNull 一般作用在 Integer 类型上,其还可以配合 @size、@Max、@Min 对字段的数值大小进行控制。而 @NotEmpty 表示不能为空,且长度必须大于 0 ,一般用在集合类或数组上。 @NotBlank 只能作用在 String 类型上,并且调用 trim() 后,长度必须大于 0 。
同时,使用 @NotBlank 等注解时,一定要和 @valid 一起使用,不然@NotBlank不起作用,如:
@PostMapping("/save")
@ApiOperation(value = "新增", notes = "传入supplementaryMaterial")
public ActionResult save(@Valid @RequestBody SupplementaryMaterial supplementaryMaterial) {
return new ActionResult().status(supplementaryMaterialService.save(supplementaryMaterial));
}