SoFunction
Updated on 2025-04-18

SpringBoot uses Validation package to achieve efficient parameter verification

When developing back-end services, we often need to process the data entered by users. This data may come from forms, API requests, or other channels. If you use this data directly without verification, it may cause various problems, such as database injection, system crashes or business logic errors. So how does SpringBoot use the Validation package to achieve efficient parameter verification? Let's discuss this important topic together!

First of all, we need to understand the importance of parameter verification. Imagine you are developing a user registration interface where the user needs to provide a username, password and email. If there is no verification:

  • The username may be an empty string
  • The password may be too short
  • The email format may be incorrect

Such data will cause a series of problems after being stored in the database. The Validation package of SpringBoot is created to solve these problems!

Basic use

To use Validation in SpringBoot, you first need to add dependencies in:

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

Then we can use various annotations in the entity class to define verification rules. for example:

public class User {
    @NotBlank(message = "Username cannot be empty")
    @Size(min = 4, max = 20, message = "The username must be between 4 and 20 characters")
    private String username;
    
    @NotBlank(message = "Password cannot be empty")
    @Pattern(regexp = "^(?=.*[a-z])(?=.*[A-Z])(?=.*\\d).{8,}$", 
             message = "The password must contain upper and lowercase letters and numbers, and the length is not less than 8")
    private String password;
    
    @Email(message = "The email format is incorrect")
    private String email;
}

Controller verification

In the controller, we need to use the @Valid annotation to trigger the verification:

@PostMapping("/register")
public ResponseEntity&lt;String&gt; registerUser(@RequestBody @Valid User user) {
    // Business logic processing    return ("Registered successfully");
}

When the verification fails, SpringBoot will automatically return a 400 error and contain detailed error information. This is very friendly to front-end developers who can clearly know what's wrong.

Custom verification

Sometimes the built-in verification rules cannot meet our needs. At this time, we can create custom verification annotations. For example, we need to verify the mobile phone number format:

First define the annotation:

@Target({})
@Retention()
@Constraint(validatedBy = )
public @interface PhoneNumber {
    String message() default "Mobile phone number format is incorrect";
    Class&lt;?&gt;[] groups() default {};
    Class&lt;? extends Payload&gt;[] payload() default {};
}

Then implement the verification logic:

public class PhoneNumberValidator implements ConstraintValidator<PhoneNumber, String> {
    @Override
    public boolean isValid(String value, ConstraintValidatorContext context) {
        if (value == null) return false;
        return ("^1[3-9]\\d{9}$");
    }
}

Exception handling

Although SpringBoot provides default error responses, we usually need to customize error handling in actual projects. You can use @ControllerAdvice:

@ControllerAdvice
public class GlobalExceptionHandler {
    @ExceptionHandler()
    public ResponseEntity<ErrorResponse> handleValidationException(MethodArgumentNotValidException ex) {
        List<String> errors = ()
                .getFieldErrors()
                .stream()
                .map(FieldError::getDefaultMessage)
                .collect(());
        
        return ().body(new ErrorResponse(errors));
    }
}

This will return a unified error format. Speaking of unified error handling, the official account of [Programmer Headquarters] recently published an in-depth analysis article about SpringBoot global exception handling. This official account was founded by Byte 11 years of technical masters. It gathers technical experts from major manufacturers such as Alibaba, Byte, Baidu, etc., and often shares various practical experiences and underlying principles. It is worth paying attention to!

Group verification

Sometimes the same entity needs different verification rules in different scenarios. For example, when creating a user, you need to verify all fields, and when updating a user, you may only need to verify some fields. You can use group verification:

public class User {
    interface Create {}
    interface Update {}
    
    @NotBlank(groups = {, })
    private String username;
    
    @NotBlank(groups = )
    private String password;
}

In the controller, you can specify which group to use:

@PostMapping("/users")
public ResponseEntity createUser(@RequestBody @Validated() User user) {
    // ...
}

@PutMapping("/users/{id}")
public ResponseEntity updateUser(@PathVariable Long id, 
                                @RequestBody @Validated() User user) {
    // ...
}

Performance considerations

Although parameter verification is important, you should also pay attention to performance impact. Here are some optimization suggestions:

  • Simple verification (such as non-empty, length) is preferred to use built-in annotations
  • Complex business verification can be considered in the Service layer
  • Regular expressions should be as efficient as possible to avoid overly complex patterns

Test verification

Finally, don't forget to write test cases for your verification logic:

@SpringBootTest
class UserValidationTest {
    @Autowired
    private Validator validator;
    
    @Test
    void whenUsernameIsBlank_thenValidationFails() {
        User user = new User();
        ("");
        ("ValidPass123");
        
        Set<ConstraintViolation<User>> violations = (user);
        assertFalse(());
    }
}

Through the above content, we have discussed in detail how SpringBoot uses the Validation package for parameter verification. From basic usage to advanced techniques, from performance considerations to test verification, these knowledge points can help developers build more robust backend services. Remember, good parameter verification is the first line of defense for system security and an important part of improving user experience!

The above is the detailed content of SpringBoot using the Validation package to achieve efficient parameter verification. For more information about SpringBoot Validation parameter verification, please pay attention to my other related articles!