Spring Boot Validation Interview Questions and Answers
Master Spring Boot Validation with interview questions covering Bean Validation, Jakarta Validation, @Valid, @Validated, custom validators, validation groups, nested validation, MethodArgumentNotValidException, and production best practices.
Introduction
Validation is one of the most important aspects of enterprise applications.
It ensures that only valid and consistent data enters the system before any business logic is executed.
Without validation, applications may suffer from:
- Invalid customer data
- Database inconsistencies
- Security vulnerabilities
- Business rule violations
- Runtime exceptions
Spring Boot integrates with Jakarta Bean Validation (Jakarta Validation API) and Hibernate Validator to provide declarative validation.
Validation is commonly applied to:
- REST APIs
- DTOs
- Request Parameters
- Path Variables
- Service Methods
- Configuration Properties
Validation Architecture
flowchart LR
Client --> Controller
Controller --> Validation
Validation --> Success
Validation --> ValidationException
Success --> Service
ValidationException --> GlobalExceptionHandler
GlobalExceptionHandler --> ErrorResponse
Q1. What is Bean Validation?
Answer
Bean Validation is the standard Java validation specification (Jakarta Validation).
Spring Boot uses Hibernate Validator as its default implementation.
Dependency
<dependency>
<groupId>
org.springframework.boot
</groupId>
<artifactId>
spring-boot-starter-validation
</artifactId>
</dependency>
Benefits
- Declarative validation
- Less boilerplate
- Standard annotations
- Automatic request validation
Q2. What is @Valid?
@Valid triggers validation for request objects.
Example
@PostMapping
public Customer save(
@Valid
@RequestBody
CustomerRequest request){
}
Flow
flowchart TD
Request --> Validation
Validation --> Success
Validation --> MethodArgumentNotValidException
Success --> Controller
If validation fails,
Spring throws MethodArgumentNotValidException.
Q3. What is @Validated?
@Validated is a Spring annotation that supports:
- Validation Groups
- Method Validation
- Class-level validation
Example
@Service
@Validated
public class CustomerService {
}
Difference
| @Valid | @Validated |
|---|---|
| Jakarta Validation | Spring Validation |
| No groups | Supports validation groups |
| Common for DTOs | Common for services |
Q4. What are commonly used validation annotations?
| Annotation | Purpose |
|---|---|
| @NotNull | Cannot be null |
| @NotBlank | Non-empty string |
| @NotEmpty | Collection/String not empty |
| @Size | Length validation |
| @Min | Minimum value |
| @Max | Maximum value |
| @Positive | Positive number |
| Email validation | |
| @Pattern | Regex validation |
| @Past | Date must be in past |
| @Future | Date must be in future |
Example
@NotBlank
private String name;
@Email
private String email;
@Min(18)
private int age;
Q5. How do you validate nested objects?
Use @Valid on nested fields.
Example
public class Customer{
@Valid
private Address address;
}
Nested Validation
flowchart LR
Customer --> Address
Address --> Validation
Validation --> Success
Validation cascades to nested objects automatically.
Q6. What are Validation Groups?
Validation Groups apply different rules in different scenarios.
Example
public interface Create{
}
public interface Update{
}
Usage
@NotNull(
groups = Update.class)
Typical scenarios
- Create
- Update
- Admin Operations
Q7. How do you create a Custom Validator?
Step 1
Create annotation
@Target(
FIELD)
@Retention(
RUNTIME)
public @interface
ValidAccount{
}
Step 2
Implement validator
public class
AccountValidator
implements
ConstraintValidator
Typical use cases
- Account Number
- PAN Number
- IFSC Code
- Aadhaar
- Business Rules
Q8. How are Validation Errors handled?
Validation failures throw
MethodArgumentNotValidException
Global Handler
@ExceptionHandler(
MethodArgumentNotValidException.class)
Flow
flowchart TD
Request --> Validation
Validation --> Exception
Exception --> GlobalExceptionHandler
GlobalExceptionHandler --> JSONError
Q9. How do you validate Path Variables and Request Parameters?
Example
@GetMapping(
"/customers/{id}")
public Customer find(
@PathVariable
@Positive
Long id){
}
Example
@RequestParam
@NotBlank
String name
Enable method validation
@Validated
@RestController
Q10. Validation Best Practices
Validate DTOs
Avoid validating entity classes directly.
Use Bean Validation
Avoid manual if validations.
Create Custom Validators
For business-specific rules.
Return Standard Error Responses
Use ProblemDetail or a consistent API error model.
Keep Validation Close to Input
Validate at API boundaries before invoking business logic.
Banking Example
flowchart TD
TransferRequest --> Validation
Validation --> Success
Validation --> ErrorResponse
Success --> TransferService
TransferService --> Database
Only validated requests reach the service layer.
Common Interview Questions
- What is Bean Validation?
- What is
@Valid? - What is
@Validated? @Validvs@Validated?- What are Validation Groups?
- How do you validate nested objects?
- How do you create custom validators?
- How are validation exceptions handled?
- How do you validate path variables?
- Validation best practices?
Quick Revision
| Topic | Summary |
|---|---|
| Bean Validation | Jakarta Validation API |
| Hibernate Validator | Default implementation |
| @Valid | Validate request object |
| @Validated | Spring validation + groups |
| Validation Groups | Different rules per scenario |
| Custom Validator | Business validation |
| Nested Validation | Cascade using @Valid |
| MethodArgumentNotValidException | Validation failure |
| ProblemDetail | Standard validation error response |
| DTO Validation | Recommended practice |
Validation Lifecycle
sequenceDiagram
Client->>Controller: HTTP Request
Controller->>Validation Engine: Validate DTO
Validation Engine-->>Controller: Success
Controller->>Service: Business Logic
Service-->>Controller: Response
Controller-->>Client: Success Response
Production Example – Banking Account Registration
A customer submits a new account registration request.
Validation Rules
- Name must not be blank.
- Email must be valid.
- Age must be at least 18.
- Mobile number must match the organization's format.
- Address object is validated recursively.
- PAN number is validated using a custom validator.
If validation fails
- Spring throws
MethodArgumentNotValidException. @RestControllerAdvicecatches the exception.- A ProblemDetail response is returned.
- The service layer is never invoked.
flowchart LR
MobileApp --> RegistrationAPI
RegistrationAPI --> BeanValidation
BeanValidation --> Success
BeanValidation --> ValidationError
Success --> RegistrationService
ValidationError --> GlobalExceptionHandler
GlobalExceptionHandler --> ProblemDetail
This approach prevents invalid data from entering the business layer and ensures consistent error handling.
Key Takeaways
- Spring Boot uses Jakarta Bean Validation with Hibernate Validator as the default implementation.
@Validvalidates request objects, while@Validatedadds support for validation groups and method-level validation.- Standard validation annotations such as
@NotBlank,@Email,@Size, and@Positivesimplify input validation. - Nested objects can be validated recursively using
@Valid. - Validation Groups allow different rules for operations such as create, update, and administrative workflows.
- Custom validators support organization-specific business rules such as account numbers or regulatory identifiers.
- Validation failures should be handled centrally using
@RestControllerAdviceand ProblemDetail. - Validate DTOs at API boundaries to improve application security, maintainability, and data integrity.