您的位置:首页 > 编程语言 > Java开发

@NotNull, @NotEmpty和@NotBlank

2017-05-02 00:00 537 查看
在Byte类型上使用了@NotEmpty,运行到这里的时候报错,报错信息大致如下:

No validator could be found for constraint 'javax.validation.constraints.Size' validating type 'java.lang.Byte'. Check configuration for 'licenseType'

遂查看了@NotNull, @NotEmpty, 和@NotBlank三种注解类型的适用场景:

1. @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

@NotNull适用于任何类型,被注解的元素必须不能是null

2. @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

@NotEmpty适用于String,Collection,Map或者Array,不能为null或empty(从最短长度为1也能看出)

@NotEmpty的元素首先肯定是@NotNull的

3. @NotBlank

/**
* Validate that the annotated string is not {@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

@NotBlank与@NotEmpty的区别是:

@NotBlank只能用在String上

@NotBlank会忽略尾部的空格(如果只有空格,@NotEmpty认为不是empty的,而@NotBlank会认为是empty的)

@NotBlank的String首先肯定是@NotEmpty的
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  Java Annotation Spring