Complete Guide to Spring Boot Annotations with Explanations and Examples
(...existing content...)
---
5. Validation Annotations (javax.validation / jakarta.validation)
@Valid
Purpose:
Used to trigger validation on an object passed as a parameter in a controller or service method.
Example:
@PostMapping("/users")
public ResponseEntity<?> createUser(@Valid @RequestBody User user) {
return ResponseEntity.ok(userService.save(user));
@NotNull, @NotEmpty, @NotBlank
Purpose:
Validate that fields are not null or empty:
- @NotNull Value must not be null.
- @NotEmpty Value must not be null and must not be empty (applies to strings, collections).
- @NotBlank Value must not be null, empty, or whitespace (applies to strings).
Example:
public class User {
@NotBlank(message = "Name is required")
private String name;
@Size
Purpose:
Restricts the size (length for Strings, size for collections).
Example:
@Size(min = 8, message = "Password must be at least 8 characters")
private String password;
@Email
Purpose:
Ensures the field has a valid email format.
Example:
@Email(message = "Invalid email")
private String email;
@Min and @Max
Purpose:
Restrict a numeric value within minimum and maximum bounds.
Example:
@Min(18)
@Max(60)
private int age;
... (and so on for JPA, Security, AOP, Lifecycle, and Testing annotations)