0
0
Spring Bootframework~15 mins

@NotNull, @NotBlank, @NotEmpty in Spring Boot - Deep Dive

Choose your learning style9 modes available
Overview - @NotNull, @NotBlank, @NotEmpty
What is it?
@NotNull, @NotBlank, and @NotEmpty are annotations used in Spring Boot to check that data meets certain rules before the program uses it. They help make sure values are not missing or empty when they shouldn't be. Each annotation checks a different kind of emptiness or null value in data like text or collections. This helps avoid errors and keeps data clean and reliable.
Why it matters
Without these checks, programs might try to use missing or empty data, causing crashes or wrong results. These annotations save time by automatically checking data and giving clear error messages. They make apps safer and easier to maintain, especially when many users or systems send data. Without them, developers would write lots of manual checks, increasing mistakes and slowing development.
Where it fits
Before learning these, you should understand basic Java and Spring Boot setup, especially how to create classes and use annotations. After this, you can learn about custom validation, error handling, and how to connect validation with user interfaces or APIs. This topic fits into the bigger picture of making robust, user-friendly applications.
Mental Model
Core Idea
These annotations act like gatekeepers that stop invalid or empty data from entering your program, each with a specific rule about what 'empty' means.
Think of it like...
Imagine a security guard checking people entering a building: @NotNull checks if someone is present at all, @NotEmpty checks if their bag isn't empty, and @NotBlank checks if the bag has something meaningful inside, not just empty wrappers.
┌───────────────┐
│   Input Data  │
└──────┬────────┘
       │
       ▼
┌───────────────┐
│  @NotNull     │  Checks value is not null
└──────┬────────┘
       │
       ▼
┌───────────────┐
│  @NotEmpty    │  Checks collection or string is not empty
└──────┬────────┘
       │
       ▼
┌───────────────┐
│  @NotBlank    │  Checks string has non-whitespace chars
└───────────────┘
       │
       ▼
┌───────────────┐
│ Valid Data    │
└───────────────┘
Build-Up - 7 Steps
1
FoundationUnderstanding @NotNull Basics
🤔
Concept: Learn what @NotNull does and when to use it.
The @NotNull annotation ensures that a value is not null. It means the value must exist but can be empty if it's a string or collection. For example, if you have a user’s age field, @NotNull makes sure the age is provided, not missing. Example: public class User { @NotNull private Integer age; }
Result
If age is missing (null), validation fails and an error is reported.
Understanding that @NotNull only checks for presence, not content, helps avoid confusion when empty strings or collections pass this check.
2
FoundationIntroducing @NotEmpty for Collections and Strings
🤔
Concept: Learn how @NotEmpty checks that strings or collections are not empty.
The @NotEmpty annotation checks that a string or collection is not empty. It means the value must exist and have at least one element or character. For example, a list of emails annotated with @NotEmpty must have at least one email. Example: public class EmailList { @NotEmpty private List emails; }
Result
If emails is null or an empty list, validation fails.
Knowing @NotEmpty checks both null and emptiness prevents bugs where empty collections sneak through @NotNull checks.
3
IntermediateUsing @NotBlank for Meaningful Text
🤔Before reading on: Do you think @NotBlank allows strings with only spaces? Commit to yes or no.
Concept: @NotBlank ensures strings have actual visible characters, not just spaces.
The @NotBlank annotation is stricter than @NotEmpty for strings. It checks that the string is not null, not empty, and contains at least one non-whitespace character. For example, a username field with @NotBlank rejects " " (spaces only). Example: public class User { @NotBlank private String username; }
Result
Strings with only spaces or empty strings fail validation.
Understanding @NotBlank’s focus on meaningful content helps prevent accepting useless or misleading input.
4
IntermediateComparing @NotNull, @NotEmpty, and @NotBlank
🤔Before reading on: Which annotation would accept an empty string ""? Commit to your answer.
Concept: Learn the differences and appropriate use cases for each annotation.
Summary: - @NotNull: Value must exist but can be empty string or empty collection. - @NotEmpty: Value must exist and not be empty (string length > 0 or collection size > 0). - @NotBlank: For strings only, must exist, not empty, and contain non-whitespace characters. Use @NotNull for objects that must be present. Use @NotEmpty for collections or strings that must have content. Use @NotBlank for strings that must have visible characters.
Result
Choosing the right annotation prevents invalid data from passing unnoticed.
Knowing these differences avoids common validation mistakes and improves data quality.
5
IntermediateApplying Annotations in Spring Boot Validation
🤔
Concept: Learn how to use these annotations with Spring Boot’s validation framework.
Spring Boot uses these annotations with the javax.validation API and Hibernate Validator by default. To activate validation: 1. Add @Valid on method parameters in controllers. 2. Annotate fields with @NotNull, @NotEmpty, or @NotBlank. 3. Handle validation errors with BindingResult or @ExceptionHandler. Example: @PostMapping("/users") public ResponseEntity createUser(@Valid @RequestBody User user, BindingResult result) { if (result.hasErrors()) { return ResponseEntity.badRequest().body(result.getAllErrors()); } return ResponseEntity.ok(user); }
Result
Invalid input triggers clear error messages before business logic runs.
Understanding integration with Spring Boot validation enables automatic and consistent data checks.
6
AdvancedCustomizing Validation Messages and Groups
🤔Before reading on: Can you customize error messages for these annotations without changing code? Commit to yes or no.
Concept: Learn how to customize error messages and use validation groups for different scenarios.
Each annotation supports a message attribute to customize the error text. Example: @NotNull(message = "Age is required") private Integer age; Validation groups let you apply different rules in different contexts by defining interfaces and specifying groups in annotations and validation calls. Example: public interface CreateGroup {} public interface UpdateGroup {} @NotNull(groups = CreateGroup.class) private String name; Use @Validated(CreateGroup.class) in controller methods to apply specific rules.
Result
Validation errors show user-friendly messages and adapt to different use cases.
Knowing how to customize messages and groups improves user experience and flexibility.
7
ExpertUnderstanding Annotation Processing Internals
🤔Before reading on: Do you think these annotations run checks at compile time or runtime? Commit to your answer.
Concept: Explore how Spring Boot and Hibernate Validator process these annotations at runtime.
These annotations are processed at runtime by the validation framework. When validation is triggered, the framework uses reflection to inspect annotated fields and applies rules accordingly. Hibernate Validator implements the logic for each annotation. The process: 1. Spring calls the validator on the object. 2. Validator scans fields for annotations. 3. For each annotation, it runs the corresponding check. 4. Collects errors and returns them. This runtime approach allows flexible validation but adds some overhead.
Result
Validation happens automatically during program execution, not before.
Understanding runtime processing clarifies performance impacts and debugging strategies.
Under the Hood
At runtime, Spring Boot uses the Bean Validation API (JSR 380) with Hibernate Validator as the default implementation. When an object is validated, the validator uses Java reflection to find fields annotated with @NotNull, @NotEmpty, or @NotBlank. Each annotation corresponds to a validator class that implements the logic to check the field’s value. For example, @NotNull’s validator checks if the value is null, @NotEmpty checks if the value is null or empty (for strings or collections), and @NotBlank trims the string and checks for non-whitespace characters. Validation results are collected and returned as constraint violations.
Why designed this way?
This design separates validation rules from business logic, making code cleaner and reusable. Using annotations allows declarative validation directly on data models. Runtime processing via reflection provides flexibility to validate any object without code changes. Alternatives like manual checks or compile-time validation were less flexible or more complex. The Bean Validation API standardizes validation across Java frameworks, promoting consistency.
┌───────────────┐
│  Spring Boot  │
│  Controller   │
└──────┬────────┘
       │ calls validate()
       ▼
┌───────────────┐
│ Bean Validator│
│ (Hibernate)   │
└──────┬────────┘
       │ uses reflection
       ▼
┌───────────────┐
│  Data Object  │
│  with @NotNull│
│  @NotEmpty    │
│  @NotBlank    │
└───────────────┘
       │
       ▼
┌───────────────┐
│ Validator Impl│
│ Checks values │
└───────────────┘
       │
       ▼
┌───────────────┐
│ Validation    │
│ Results       │
└───────────────┘
Myth Busters - 4 Common Misconceptions
Quick: Does @NotNull reject empty strings ""? Commit to yes or no.
Common Belief:People often think @NotNull rejects empty strings because they are 'empty'.
Tap to reveal reality
Reality:@NotNull only rejects null values; empty strings "" are allowed.
Why it matters:This misconception can cause bugs where empty strings pass validation unexpectedly, leading to invalid data.
Quick: Does @NotEmpty allow strings with only spaces? Commit to yes or no.
Common Belief:Some believe @NotEmpty rejects strings with only spaces because they look empty.
Tap to reveal reality
Reality:@NotEmpty only checks length > 0; strings with spaces pass validation.
Why it matters:This can allow meaningless input like " " to pass, causing data quality issues.
Quick: Can @NotBlank be used on collections? Commit to yes or no.
Common Belief:Many think @NotBlank works on collections like lists or sets.
Tap to reveal reality
Reality:@NotBlank only works on strings; it does not validate collections.
Why it matters:Using @NotBlank on collections has no effect, leading to false confidence in validation.
Quick: Are these annotations checked automatically without configuration? Commit to yes or no.
Common Belief:Some assume just adding annotations is enough for validation to happen.
Tap to reveal reality
Reality:Validation requires explicit triggering, like @Valid in Spring controllers.
Why it matters:Without proper setup, invalid data can bypass validation, causing runtime errors.
Expert Zone
1
Validation annotations can be combined with custom validators to handle complex rules beyond simple null or empty checks.
2
Validation groups allow different rules for create vs update operations, avoiding redundant or conflicting validations.
3
The order of validation and how multiple annotations interact can affect error messages and performance, which experts optimize carefully.
When NOT to use
Avoid these annotations when validation depends on external data or complex logic; use programmatic validation or custom validators instead. Also, for performance-critical code paths, minimize runtime reflection by caching or manual checks.
Production Patterns
In production, these annotations are used with global exception handlers to return user-friendly error responses. They are combined with DTOs to separate validation from database entities. Experts also use validation groups and message internationalization for multi-language support.
Connections
Design by Contract
Builds-on
These annotations implement the idea of specifying clear rules (contracts) for data inputs, ensuring software behaves correctly by enforcing preconditions.
Data Sanitization
Complementary
Validation checks data correctness, while sanitization cleans data; together they ensure safe and reliable input handling.
Quality Control in Manufacturing
Analogous process
Just like quality control inspects products for defects before shipping, these annotations inspect data before processing, preventing errors downstream.
Common Pitfalls
#1Using @NotNull expecting it to reject empty strings.
Wrong approach:public class User { @NotNull private String name; // expects non-empty but allows "" }
Correct approach:public class User { @NotBlank private String name; // rejects null, "", and whitespace }
Root cause:Confusing null with empty string leads to wrong annotation choice.
#2Applying @NotBlank on a collection field.
Wrong approach:public class Group { @NotBlank private List members; // ineffective }
Correct approach:public class Group { @NotEmpty private List members; // correctly checks collection not empty }
Root cause:Misunderstanding that @NotBlank only works on strings.
#3Forgetting to add @Valid in controller method parameters.
Wrong approach:@PostMapping("/add") public ResponseEntity addUser(@RequestBody User user) { // no validation triggered }
Correct approach:@PostMapping("/add") public ResponseEntity addUser(@Valid @RequestBody User user) { // validation triggered }
Root cause:Assuming annotations alone trigger validation without explicit activation.
Key Takeaways
@NotNull, @NotEmpty, and @NotBlank are validation annotations that check for different kinds of empty or missing data.
@NotNull only rejects null values, allowing empty strings or collections; @NotEmpty rejects null and empty strings or collections; @NotBlank rejects null, empty, and whitespace-only strings.
These annotations work at runtime via Spring Boot’s validation framework and require explicit triggering with @Valid.
Choosing the right annotation prevents bugs and improves data quality, while customizing messages and groups enhances user experience.
Understanding their internal processing and limitations helps write efficient, maintainable, and robust validation logic.