Differences between @NotEmpty, @NotNull, and @NotBlank

1. The main differences between the three are as follows:

  •  @NotEmpty : used for collection classes, cannot be null, and size>0
  •  @NotNull: cannot be null, but can be empty, no size constraints
  •  @NotBlank: only for String, not null, and size>0 after trim()

2. By viewing the source code comments are as follows:

@NotEmpty

/**
* Asserts that the annotated string, collection, map or array is not {@code null} or empty.
*
* @author Emmanuel Bernard
* @author Hardy Ferentschik
*/

 

That is to say, the String class, Collection, Map, and array with @NotEmpty added cannot be null or have a length of 0. (isEmpty() method of String, Collection, Map)

@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
*/

Unlike {@code NotEmpty}, trailing spaces are ignored, that is, Strings with pure spaces are also illegal. That's why it is said that @NotBlank is used for String.

@NotNull

/**
* The annotated element must not be {@code null}.
* Accepts any type.
*
* @author Emmanuel Bernard
*/

 

i.e. cannot be null.

3. Example:

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

 

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324820973&siteId=291194637