Spring 中@NotNull, @NotEmpty和@NotBlank之間的區別是什么?


摘自:https://www.cnblogs.com/Terry-Wu/p/8134732.html


 

示例:

String name = null;
@NotNull: false
@NotEmpty: false
@NotBlank: false

String name = "";
@NotNull: true
@NotEmpty: false
@NotBlank: false

String name = " ";
@NotNull: true
@NotEmpty: true
@NotBlank: false

String name = "Great answer!";
@NotNull: true
@NotEmpty: true
@NotBlank: true

  


 

簡述三者區別

@NotNull://CharSequence, Collection, Map 和 Array 對象不能是 null, 但可以是空集(size = 0)。  
@NotEmpty://CharSequence, Collection, Map 和 Array 對象不能是 null 並且相關對象的 size 大於 0。  
@NotBlank://String 不能是 null 且去除兩端空白字符后的長度(trimmed length)大於 0。 

  


注解的定義(在version 4.1中):

1、@NotNull:

定義如下:
@Constraint(validatedBy = {NotNullValidator.class})
這個類中有一個isValid方法是這么定義的:
public boolean isValid(Object object, ConstraintValidatorContext constraintValidatorContext) {  
 return object != null;    
} 
對象不是null就行,其他的不保證。

 

2、@NotEmpty:

定義如下:
@NotNull    
@Size(min = 1)    

也就是說,@NotEmpty除了@NotNull之外還需要保證@Size(min=1),這也是一個注解,這里規定最小長度等於1,也就是類似於集合非空。

  

3、@NotBlank:

@NotNull    
@Constraint(validatedBy = {NotBlankValidator.class})   

類似地,除了@NotNull之外,還有一個類的限定,這個類也有isValid方法:

if ( charSequence == null ) {  //curious   
  return true;     
}     
return charSequence.toString().trim().length() > 0; 

  

有意思的是,當一個string對象是null時方法返回true,但是當且僅當它的trimmed length等於零時返回false。即使當string是null時該方法返回true,但是由於@NotBlank還包含了@NotNull,所以@NotBlank要求string不為null。

  


 

 

 

  


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM