业务场景模拟:
在我们web后端的开发过程中通常会对RequestBody中某些字段进行非空校验,所以会用到下列三个注解:
@NotNull , @NotEmpty , @NotBlank
使用实例代码:
public class CreateAccessRequest implements Serializable {
private static final long serialVersionUID = -8724111111971704488L;
@NotEmpty(message = "Missing Mandatory Field")
private String applicationCode;
@NotBlank(message = "Missing Mandatory Field")
private String partnerCode;
@NotNull(message = "Missing Mandatory Field")
private String accessCode;
}
区别分析:
注解英文注释:
@NotNull: The CharSequence, Collection, Map or Array object is not null,
but can be empty.
@NotEmpty: The CharSequence, Collection, Map or Array object is not null
and size > 0.
@NotBlank: The string is not null and the trimmed length is greater than
zero.
英文注释的自我理解:
@NotNull: 不能为null,但是可以为Empty(个人理解就是可以为空格(不限制个数)或Tab)
即:(""," "," ")
@NotEmpty: 不能为null,但是可以为Empty且长度必须大于0
即:(" "," ")
@NotBlank: 只能使用在String上,不能为Null,而且调用trim()后,长度必须大于0
即:必须有实际字符 如:("test")
结合代码实例的结论如下:
1.String example = null;
@NotNull: false
@NotEmpty:false
@NotBlank:false
2.String example = "";
@NotNull:true
@NotEmpty: false
@NotBlank: false
3.String example = " ";
@NotNull: true
@NotEmpty: true
@NotBlank: false
4.String example = "Mandatory(强制性)";
@NotNull: true
@NotEmpty:true
@NotBlank:true