6.1 Overview of Bean Validation
In software development, data validation is an essential process for maintaining the stability and security of the system. Before the values passed by the client enter the business logic, it's necessary to ensure that they satisfy the correct format and constraints.
Why Validate Outside the Controller?
In the past, data was often validated using numerous if statements inside the controller or service layers.
@PostMapping("/users")
public ResponseEntity<?> createUser(@RequestBody UserDto userDto) {
if (userDto.getName() == null || userDto.getName().trim().isEmpty()) {
return ResponseEntity.badRequest().body("Name is required.");
}
if (userDto.getAge() < 0) {
return ResponseEntity.badRequest().body("Age must be greater than 0.");
}
// Execute business logic...
}
This approach causes several serious problems:
- Decreased Readability: Validation logic takes up more space than the actual business logic.
- Duplication: The same validation code must be written every time the same data object (
UserDto) is used. - Violation of the Single Responsibility Principle (SRP): The controller's main role is to process requests and return responses, but it also takes on the burden of validation.
The Advent of Bean Validation
To solve these problems, the Java ecosystem introduced the Bean Validation (JSR-380) standard, which specifies constraints by attaching annotations to the fields of an object. Spring Boot adopts Hibernate Validator, an implementation of this standard, by default.
public class UserDto {
@NotBlank(message = "Name is required.")
private String name;
@Min(value = 0, message = "Age must be greater than 0.")
private int age;
}
In the controller, simply adding the @Valid or @Validated annotation before the parameter allows the Spring application to automatically perform data binding and validation before the DispatcherServlet passes the request to the controller. If validation fails, an error response (400 Bad Request) is immediately returned to the user. Thanks to this, the business logic can focus purely on its core role.