SpringBoot

[Spring Boot] @NotNull, @NotEmpty, @NotBlank

simba 2021. 3. 10. 15:55

API Parameter Validation 체크 비교 (@NotNull, @NotEmpty, @NotBlank)

 

@NotNull

모든 데이터 타입에 대해 null체크

public class UserNotNull {
       @NotNull(message = "Name may not be null")
        private String name;

       // standard constructors / getters / toString
}

 

@NotEmpty

 

  • CharSequence (length of character sequence is evaluated)
  • Collection (collection size is evaluated)
  • Map (map size is evaluated)
  • Array (array length is evaluated)

null과 ""를 허용하지 않는다

(+ @Size 와 함께 하면 더욱 제한적일 수 있다)

 

@NotEmpty(message = "Name may not be empty")
@Size(min = 2, max = 32, message = "Name must be between 2 and 32 characters long")
private String name;

 

@NotBlank

null과 ""와 " "(빈공백문자열)를 허용하지 않는다.

public class UserNotBlank {      
       @NotBlank(message = "Name may not be blank")
       private String name;

       // standard constructors / getters / toString
}

 


  • @NotNull: a constrained CharSequence, Collection, Map, or Array is valid as long as it's not null, but it can be empty
  • @NotEmpty: a constrained CharSequence, Collection, Map, or Array is valid as long as it's not null and its size/length is greater than zero
  • @NotBlank: a constrained String is valid as long as it's not null and the trimmed length is greater than zero