@NotNull , @NotEmpty , @NotBlank 之间的区别

业务场景模拟:

           在我们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

                    

 

 

 

 

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值