@NotBlank的注释
The annotated element must not be null
and must contain at least one non-whitespace character. Accepts CharSequence
.
只用于字符串String,字符串不能为null,并且不能为空字符串,例:""," "
/**
* The annotated element must not be {@code null} and must contain at least one
* non-whitespace character. Accepts {@code CharSequence}.
*
* @author Hardy Ferentschik
* @since 2.0
*
* @see Character#isWhitespace(char)
*/
@Documented
@Constraint(validatedBy = { })
@Target({ METHOD, FIELD, ANNOTATION_TYPE, CONSTRUCTOR, PARAMETER, TYPE_USE })
@Retention(RUNTIME)
@Repeatable(List.class)
public @interface NotBlank {
......
}
}
@NotEmpty的注释
The annotated element must not be null
nor empty. Supported types are:
CharSequence
(length of character sequence is evaluated)Collection
(collection size is evaluated)Map
(map size is evaluated)- Array (array length is evaluated)
只用于字符串、集合、map、数组,且不能为null,并且长度或者大小大于1
/**
* The annotated element must not be {@code null} nor empty. Supported types are:
* <ul>
* <li>{@code CharSequence} (length of character sequence is evaluated)</li>
* <li>{@code Collection} (collection size is evaluated)</li>
* <li>{@code Map} (map size is evaluated)</li>
* <li>Array (array length is evaluated)</li>
* </ul>
*
* @author Emmanuel Bernard
* @author Hardy Ferentschik
*
* @since 2.0
*/
@Documented
@Constraint(validatedBy = { })
@Target({ METHOD, FIELD, ANNOTATION_TYPE, CONSTRUCTOR, PARAMETER, TYPE_USE })
@Retention(RUNTIME)
@Repeatable(List.class)
public @interface NotEmpty {
........
}
@NotNull的注释
The annotated element must not be null
. Accepts any type.
适用于所有类型,且不能为null
/**
* The annotated element must not be {@code null}.
* Accepts any type.
*
* @author Emmanuel Bernard
*/
@Target({ METHOD, FIELD, ANNOTATION_TYPE, CONSTRUCTOR, PARAMETER, TYPE_USE })
@Retention(RUNTIME)
@Repeatable(List.class)
@Documented
@Constraint(validatedBy = { })
public @interface NotNull {
.....
}
总结:
@NotBlank 只用于字符串String,字符串不能为null,并且不能为空字符串
@NotEmpty 只用于字符串、集合、map、数组,且不能为null,并且长度或者大小大于1
@NotNull 适用于所有类型,且不能为null
配合@valid使用,直接看代码
@RestController
public class ItemController {
@RequestMapping("/item/add")
public void addItem(@Valid Item item) {
doSomething();
}
}
public class Item {
@NotNull(message = "id不能为空")
@Min(value = 1, message = "id必须为正整数")
private Long id;
@Valid
@NotNull(message = "props不能为空")
@Size(min = 1, message = "props至少要有一个自定义属性")
private List<Prop> props;
}
public class Prop {
@NotBlank(message = "pidName不能为空")
private String pidName;
@NotBlank(message = "vidName不能为空")
private String vidName;
}
自定义校验参考:http://t.csdn.cn/FzpNK