SoFunction
Updated on 2025-04-14

SpringBoot uses @Validated annotation to achieve parameter verification elegantly

​1. Why parameter verification is needed

When developing web applications, the legality verification of user input is the basis for ensuring system stability. The traditional practice is to judge parameters one by one through the if-else statement, but the code is bloated, poor readability and easy to miss verification logic. ​Spring Boot's @Validated annotation provides a more elegant solution, combining the JSR-303/380 specification to achieve complex verification with just simple annotations.

2. The core usage of Validated

​1. Basic verification

Add verification annotations (such as @NotBlank, @Email) on the entity class field and add @Validated before the controller method parameters to automatically trigger the verification.

Sample code:

// Entity classpublic class UserDTO {  
    @NotBlank(message = "Username cannot be empty")  
    @Size(min = 3, max = 20, message = "Length requires 3-20 digits")  
    private String username;  
    
    @Email(message = "Emailbox format error")  
    private String email;  
}  

// Controller@RestController  
public class UserController {  
    @PostMapping("/register")  
    public String register(@Validated @RequestBody UserDTO user) {  
        return "Registered successfully!";  // Execute after verification    }  
}  

Effect: If the parameters are illegal, the error message will be returned directly and will not enter the method body.

2. Group verification

Set different verification rules for different scenarios (such as new and updated), and fine control is achieved through groups parameters.

Sample code:

public interface ValidationGroups {  
    interface Insert extends Default {}  // Add new grouping    interface Update extends Default {}  // Update grouping}  

public class Project {  
    @NotBlank(groups = , message = "ID cannot be empty")  
    private String id;  
    
    @Min(value = 1000, groups = , message = "The budget cannot be less than 1000")  
    private int budget;  
}  

​​​​​​​// Controller@RestController  
public class ProjectController {  
    @PostMapping("/add")  
    public String addProject(  
        @Validated() @RequestBody Project project) {  
        return "New addition was successful!";  
    }  
    
    @PostMapping("/modify")  
    public String modifyProject(  
        @Validated() @RequestBody Project project) {  
        return "The modification was successful!";  
    }  
}  

Effect: Check the budget when it is added, and check the ID when it is updated.

3. Nested verification

To perform cascade verification on nested objects, just add @Valid to the parent object field (note: @Validated cannot be used directly for nested objects).

Sample code:

public class User {  
    @NotBlank  
    private String name;  
    
    @Valid  
    private Address address;  // Nested object needs to be added @Valid}  

public class Address {  
    @NotBlank  
    private String city;  
}  

​​​​​​​// Controller@PostMapping("/user")  
public String user(@Validated @RequestBody User user) {  
    return "Check passed!";  
}  

Effect: If null, an error will be returned directly.

3. Advanced skills

​1. Custom verification annotations

When built-in annotations cannot meet the needs, you can create custom annotations. For example, check the uniqueness of the username:

step:

  • Definition annotation @UniqueUsername
  • Implement verification device UniqueUsernameValidator

Code snippet:

// Custom annotations@Target({})  
@Retention()  
@Constraint(validatedBy = )  
public @interface UniqueUsername {  
    String message() default "Username already exists";  
}  

​​​​​​​// Verifierpublic class UniqueUsernameValidator implements ConstraintValidator<UniqueUsername, String> {  
    @Override  
    public boolean isValid(String username, ConstraintValidatorContext context) {  
        // Call database or cache to verify uniqueness        return !"admin".equals(username);  // Sample logic    }  
}  

use:

public class UserDTO {  
    @UniqueUsername  
    private String username;  
}  

Effect: Verify whether the user name is duplicated.

​2. Global exception handling

The verification exception is handled uniformly through @RestControllerAdvice and the structured error message is returned:

Code example:

@RestControllerAdvice  
public class GlobalExceptionHandler {  
    @ExceptionHandler()  
    public Map<String, String> handleValidationExceptions(  
        MethodArgumentNotValidException ex) {  
        Map<String, String> errors = new HashMap<>();  
        ().getAllErrors().forEach((error) -> {  
            String fieldName = ((FieldError) error).getField();  
            String errorMessage = ();  
            (fieldName, errorMessage);  
        });  
        return errors;  
    }  
}  

Effect: Returns JSON format error message, such as {"username": "Username cannot be empty"}.

4. Summary

@Validated not only simplifies parameter verification logic, but also provides strong scalability through grouping, nested checks and custom annotations. Combined with global exception handling, developers can focus on business logic rather than duplicate verification code.

Practical suggestions:

Add dependencies in :

<dependency>  
    <groupId></groupId>  
    <artifactId>spring-boot-starter-validation</artifactId>  
</dependency>  

Priority is given to @Validated (specific to Spring), and complex scenarios are combined with @Valid (Java standard).

This is the article about SpringBoot using @Validated annotation to elegantly implement parameter verification. For more related SpringBoot @Validated parameter verification content, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!