最近開始學習java 記錄一些筆記
區別:
@NotNull://CharSequence, Collection, Map 和 Array 對象不能是 null, 但可以是空集(size = 0)。
@NotEmpty://CharSequence, Collection, Map 和 Array 對象不能是 null 並且相關對象的 size 大於 0。
@NotBlank://String 不是 null 且去除兩端空白字符後的長度(trimmed length)大於 0。
@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.
1、@NotNull:不能爲null,但可以爲empty eg (""," "," ")
定義:
@Constraint(validatedBy = {NotNullValidator.class})
這個類中有一個isValid方法
public boolean isValid(Object object, ConstraintValidatorContext constraintValidatorContext) {
return object != null;
}
對象不是null就行,其他的不保證。
2、@NotEmpty:不能爲null,而且長度必須大於0 eg (" "," ")
定義:
@NotNull @Size(min = 1)
@NotEmpty除了@NotNull之外還需要保證@Size(min=1),這也是一個註解,這裏規定最小長度等於1,也就是類似於集合非空。
3、@NotBlank:只能作用在String上,不能爲null,而且調用trim()後,長度必須大於0 eg ("test") 即:必須有實際字符
定義:
@NotNull
@Constraint(validatedBy = {NotBlankValidator.class})
這個類中有一個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。
如:
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 = "Hi Betty!";
@NotNull: true
@NotEmpty: true
@NotBlank: true
常用註解:
@Null 被註釋的元素必須爲null
@NotNull 被註釋的元素不能爲null
@AssertTrue 被註釋的元素必須爲true
@AssertFalse 被註釋的元素必須爲false
@Min(value) 被註釋的元素必須是一個數字,其值必須大於等於指定的最小值
@Max(value) 被註釋的元素必須是一個數字,其值必須小於等於指定的最大值
@DecimalMin(value) 被註釋的元素必須是一個數字,其值必須大於等於指定的最小值
@DecimalMax(value) 被註釋的元素必須是一個數字,其值必須小於等於指定的最大值
@Size(max,min) 被註釋的元素的大小必須在指定的範圍內。
@Digits(integer,fraction) 被註釋的元素必須是一個數字,其值必須在可接受的範圍內
@Past 被註釋的元素必須是一個過去的日期
@Future 被註釋的元素必須是一個將來的日期
@Pattern(value) 被註釋的元素必須符合指定的正則表達式。
@Email 被註釋的元素必須是電子郵件地址
@Length 被註釋的字符串的大小必須在指定的範圍內
@NotEmpty 被註釋的字符串必須非空
@Range 被註釋的元素必須在合適的範圍內
想到再補充