Validation Annotations
Common Annotations
public class CreateProductRequest {
@NotBlank(message = "Name is required")
@Size(min = 2, max = 100)
private String name;
@NotNull(message = "Price is required")
@Positive(message = "Price must be positive")
private BigDecimal price;
@Email(message = "Invalid email")
private String sellerEmail;
@Pattern(regexp = "^[A-Z]{2}-[0-9]{8}$")
private String productCode;
@PastOrPresent
private LocalDate manufacturingDate;
@NotEmpty
private List<String> categories;
}
Annotation Reference
| Annotation | Validation |
|---|---|
@NotNull |
Not null |
@NotBlank |
Not null, not empty, not whitespace |
@NotEmpty |
Not null, not empty (collections) |
@Size |
String/collection size bounds |
@Min/@Max |
Numeric bounds |
@Positive/@Negative |
Positive/negative numbers |
@Email |
Email format |
@Pattern |
Regex match |
@Past/@Future |
Date in past/future |
Custom Validator
@Constraint(validatedBy = UniqueEmailValidator.class)
@Target({FIELD})
@Retention(RUNTIME)
public @interface UniqueEmail {
String message() default "Email already exists";
Class<?>[] groups() default {};
Class<? extends Payload>[] payload() default {};
}
public class UniqueEmailValidator
implements ConstraintValidator<UniqueEmail, String> {
@Autowired
private UserRepository userRepository;
@Override
public boolean isValid(String email, ConstraintValidatorContext context) {
return email != null && !userRepository.existsByEmail(email);
}
}
Validation Best Practices
Validation Layers
- Client-side: Immediate feedback
- API Gateway: Basic validation
- Service: Business rules
- Database: Constraints
Types
- Type checking
- Format validation (email, phone)
- Range checking
- Length limits
- Business rules
Best Practices
- Validate on server (never trust client)
- Return specific error messages
- Use whitelist approach
- Log validation failures
Key Points
- Understanding Spring Validation is essential for production systems
- Always consider scalability and maintainability
- Test thoroughly before deploying to production
- Monitor performance and set up alerting
Common Patterns
- Validation: Always validate input at the boundary
- Error Handling: Use structured error responses
- Logging: Log key events for debugging
- Testing: Unit, integration, and load tests
- Documentation: Keep docs updated with code changes
Practice Problems
Design and implement a solution for Spring Validation in a backend system. Consider scalability, error handling, and production readiness.
Solution
// Spring Validation implementation
// Key aspects: validation, error handling, logging, testing
public class SpringValidation {
// Production-ready implementation
} Identify and handle edge cases for Spring Validation. What happens under high load, with invalid input, or during failures?
Solution
// Edge case handling:
// 1. Null/empty input -> validation
// 2. High load -> rate limiting, queuing
// 3. Failures -> retries, circuit breaker
// 4. Concurrent access -> locks, idempotency Write a testing strategy for Spring Validation. Include unit tests, integration tests, and performance tests.
Solution
// Test plan:
// - Unit: 80% coverage target
// - Integration: API contracts
// - Performance: latency, throughput
// - Chaos: failure injection Quiz
1. What is the difference between @NotBlank and @NotNull?
2. Where do you enable validation in a controller?
3. What is a common mistake when implementing Spring Validation?
Flashcards
Question
@NotBlank vs @NotNull?
Click to reveal answer
Answer
@NotBlank: not null + not empty + not whitespace. @NotNull: not null only.
Question
How to enable validation in controller?
Click to reveal answer
Answer
@Valid on @RequestBody parameter
Question
Spring Validation best practices
Click to reveal answer
Answer
Follow SOLID principles, write clean code, test thoroughly, document decisions, and monitor in production.
Revision Notes
Key Takeaways
- 1. Use @Valid on @RequestBody to enable validation
- 2. @NotBlank > @NotNull (rejects empty/whitespace)
- 3. Create custom validators with @Constraint
- 4. Return 422 Unprocessable Entity for validation errors
Interview Tips
- • Know validation annotations
- • Implement custom validators
Cheat Sheet
Validation
- @Valid: Enable on @RequestBody
- @NotBlank: Not null + not empty + not whitespace
- @NotNull: Not null only
- @Size, @Min, @Max: Bounds
- @Email, @Pattern: Format
- Custom: @Constraint + Validator class