These annotations help check if data is missing or empty before saving or using it. They keep your app safe and correct.
@NotNull, @NotBlank, @NotEmpty in Spring Boot
@NotNull @NotEmpty @NotBlank
@NotNull means the value cannot be null but can be empty if it is a string or collection.
@NotEmpty means the value cannot be null or empty (like an empty string or empty list).
@NotBlank means the value cannot be null, empty, or only spaces (only for strings).
@NotNull private Integer age;
@NotEmpty private List<String> tags;
@NotBlank private String name;
This class uses the three annotations to make sure the user has an ID, roles list, and username filled properly. The main method shows creating a user and printing the values.
import jakarta.validation.constraints.NotBlank; import jakarta.validation.constraints.NotEmpty; import jakarta.validation.constraints.NotNull; public class User { @NotNull private Integer id; @NotEmpty private List<String> roles; @NotBlank private String username; // Constructor public User(Integer id, List<String> roles, String username) { this.id = id; this.roles = roles; this.username = username; } // Getters public Integer getId() { return id; } public List<String> getRoles() { return roles; } public String getUsername() { return username; } public static void main(String[] args) { // Example usage User user = new User(1, List.of("admin", "user"), "john_doe"); System.out.println("User ID: " + user.getId()); System.out.println("Roles: " + user.getRoles()); System.out.println("Username: " + user.getUsername()); } }
These annotations work with Spring Boot's validation system and need a validator to check them at runtime.
@NotBlank only works on strings, so use @NotEmpty for collections or arrays.
Use these annotations on fields or method parameters to automatically validate input data.
@NotNull means value cannot be null but can be empty.
@NotEmpty means value cannot be null or empty (strings, collections).
@NotBlank means value cannot be null, empty, or spaces (only strings).