Validation is arguably one of the most critical aspects of enterprise application development. Imagine an Employee Management System exposing a REST API to register new staff. What happens if a client submits this payload?
Without strict validation boundaries, this corrupted data flows through your controller, into your service layer, and straight into your database—causing catastrophic business logic failures down the line.
Spring Boot elegantly solves this by seamlessly integrating with Bean Validation (Jakarta Validation), allowing you to enforce rules using simple annotations before the data ever reaches your business logic.
1. What is Bean Validation?
Standard Definition
Bean Validation is a Java specification that allows developers to define validation constraints directly on object models (DTOs) using annotations.
To enable it in Spring Boot, you include the following starter dependency. Internally, Spring Boot relies on Hibernate Validator as the default engine to execute these rules.
Why Is Validation Required?
- Prevents bad data from reaching the database.
- Dramatically improves API security (mitigating injection attacks).
- Reduces bugs by enforcing assumptions early.
- Simplifies business logic (Service classes shouldn't contain basic formatting checks).
2. Core Validation Annotations
Let's look at a standard EmployeeRequest DTO and how we validate its fields.
@NotNull
Ensures that a field is not physically null.
Valid: {"salary": 50000}
Invalid: {"salary": null} → "salary must not be null"
@NotBlank
Used strictly for Strings. It enforces three rules simultaneously: the string cannot be null, cannot be empty, and cannot consist entirely of whitespace.
Valid: {"name": "Madhu"}
Invalid: {"name": ""} or {"name": " "}
@NotEmpty
Ensures the field is not null AND its size/length is greater than 0. It works with Strings, Lists, Sets, and Maps.
The @NotNull vs @NotEmpty vs @NotBlank Debate
This is a favorite interview question. Here is exactly how they differ:
| Annotation | Null Allowed? | Empty "" Allowed? |
Spaces " " Allowed? |
|---|---|---|---|
@NotNull |
No | Yes | Yes |
@NotEmpty |
No | No | Yes |
@NotBlank |
No | No | No |
@Size & @Email & @Pattern
@Size(min=3, max=50): Enforces boundaries on Strings or Collections.@Email: Validates standard email formatting natively.@Pattern(regexp="^[0-9]{10}$"): Uses Regular Expressions to enforce strict formatting (like exactly 10 digits for a mobile number).
3. Triggering Validation Using @Valid
Important Interview Concept
Question: "I added @NotBlank to my DTO, but invalid data is still passing through. Why?"
Answer: Because validation does not run automatically. You must explicitly trigger the validation engine when the payload enters the controller.
Spring triggers validation using the @Valid annotation inside the controller method signature.
Internal Working Flow of @Valid
If the data is invalid, Spring immediately intercepts it and returns a 400 Bad Request before your controller logic ever executes.
4. Creating Custom Validators
Built-in annotations are powerful, but enterprise business rules often require custom logic.
Business Rule: An Employee ID must strictly begin with the prefix "EMP" (e.g., EMP1001 is valid, ABC1001 is invalid).
Step 1: Create the Custom Annotation
Step 2: Create the ConstraintValidator Engine
Step 3: Apply the Annotation
Real World Use Cases for Custom Validators: PAN Numbers, Indian Aadhaar Validation, GST Numbers, Advanced Password Policies, Company-specific SKU formats.
5. Complete Backend Validation Flow
6. Interview Summary Checklist
Top Interview Q&A
Q1: What is Bean Validation?
A: Bean Validation is a Jakarta specification allowing developers to declare validation rules directly on Java DTOs using annotations. Spring Boot uses Hibernate Validator as its default execution engine.
Q2: What happens internally when @Valid is used?
A: When a request arrives, Spring binds the JSON payload to the Java object. Spotting @Valid, it invokes the Hibernate Validator engine. The engine processes all constraints. If any fail, Spring aborts the controller execution and throws a MethodArgumentNotValidException, automatically returning a 400 Bad Request to the client.
Q3: What is a ConstraintValidator?
A: ConstraintValidator is the core interface used to implement the actual business logic behind a custom validation annotation. It contains the isValid() method which dictates whether the incoming data passes or fails.
Important Internal Classes to Memorize
ValidatorLocalValidatorFactoryBeanSpringValidatorAdapterConstraintValidatorMethodArgumentNotValidExceptionBindingResult
Comments
Post a Comment