@NotNull钾军、@NotEmpty鳄袍、@NotBlank的區(qū)別
大致區(qū)別如下:
@NotEmpty用在集合類上面 @NotBlank 用在String上面 @NotNull 用在基本類型上
只有簡(jiǎn)單的結(jié)果,但是再更具體一點(diǎn)的內(nèi)容就搜不到了吏恭,所以去看了看源碼拗小,發(fā)現(xiàn)了如下的注釋:
1. @NotEmpty
/** * Asserts that the annotated string,collection, map or array is not {**@code **null} or empty.
@author Emmanuel Bernard @author Hardy Ferentschik
***/
@Documented
@Constraint(validatedBy = { })
@Target({ METHOD, FIELD, ANNOTATION_TYPE, CONSTRUCTOR, PARAMETER})
@Retention(RUNTIME)
@ReportAsSingleViolation
@NotNull
@Size(min = 1)
public @interface NotEmpty {
String message() default "{org.hibernate.validator.constraints.NotEmpty.message}";
Class<?>[] groups() default { };
也就是說,加了@NotEmpty的String類樱哼、Collection哀九、Map、數(shù)組搅幅,是不能為null并且長(zhǎng)度必須大于0的(String阅束、Collection、Map的isEmpty()方法)茄唐。
2. @NotBlank
/** Validate that the annotated string isnot {@code null} or empty. The difference to {@code NotEmpty}is that trailing whitespaces are getting ignored. @author Hardy Ferentschik
***/
@Documented
@Constraint(validatedBy = { })
@Target({ METHOD, FIELD, ANNOTATION_TYPE, CONSTRUCTOR,PARAMETER })
@Retention(RUNTIME)
@ReportAsSingleViolation
@NotNull
public @interface NotBlank {
String message() default "{org.hibernate.validator.constraints.NotBlank.message}";
注意:@NotBlank用于String類型
“The difference to {@code NotEmpty} is that trailingwhitespaces are getting ignored.” –> 和{@code NotEmpty}不同的是息裸,尾部空格被忽略,也就是說沪编,純空格的String也是不符合規(guī)則的呼盆。所以才會(huì)說@NotBlank用于String,只能作用在String上蚁廓,不能為null访圃,而且調(diào)用trim()后,長(zhǎng)度必須大于0相嵌。
("test") 即:必須有實(shí)際字符
3. @NotNull
/*** The annotated element must not be {@code null}. Accepts any type.
@author Emmanuel Bernard
**/
@Target({ METHOD, FIELD, ANNOTATION_TYPE, CONSTRUCTOR, PARAMETER })
@Retention(RUNTIME)
@Documented
@Constraint(validatedBy = { })
public @interface NotNull {
String message() default "{javax.validation.constraints.NotNull.message}";
Class<?>[] groups() default { };
這個(gè)就很好理解了腿时,不能為null,但可以為empty饭宾。
examples:
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
附上一個(gè)使用例子:
@NotBlank(message = "startTime must not be null")
private String startTime;
@NotBlank(message = "endTime must not be null")
private String endTime;
@NotNull(message = "areaType must not be null")
private Integer areaType;
@NotBlank(message = "userId must not be null")
private String userId;