@NotNull @NotBlank@NotEmpty区别(看源码说话)

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/qq_26118603/article/details/81411923

写在前面

在标准点儿开发环境中,前端传递参数到后台时候往往需要js之中判断一遍,但是同时,我们后端也不能不做任何处理,也同样对前端传递过来得参数进行判断(空判断,参数长度判断,参数正则格式判断)。这样在我们前后端分离时候与前端对接接口才能更好得避免错误。网上其他博客也对这几个注解做出了使用场景区别划分,但是很多都是瞎扯,作为程序员我们还是看源码说话。

@NotNull @NotBlank@NotEmpty区别

  • @NotBlank通常作用在String类型参数上面。下面注释得意思是,参数即使是空字符串也不行,必须要有值。
/**
 * 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 {
  • @NotNull通常作用的是基本类型数据,但是它是可以接收任何类型的(Accepts any type.)
/**
 * 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 {
  • @NotEmpty通常情况下作用到Collection,Map,Array数组
/**
 * 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 {

猜你喜欢

转载自blog.csdn.net/qq_26118603/article/details/81411923