Validation
Checking input before calling the service
Successfully deserialized JSON does not automatically mean a valid request. A field may be empty, a string may be too long, or a number may be outside the allowed range. In Spring MVC, such rules can be described conveniently with Jakarta Bean Validation directly on the DTO.
record CreateUserRequest(
@NotBlank String name,
@Email String email,
@Min(18) int age) {}
@PostMapping("/users")
UserDto create(@Valid @RequestBody CreateUserRequest request) {
return userService.create(request);
}
The @NotBlank, @Email, and
@Min annotations define constraints for individual DTO components.
@Valid on the controller argument starts validation after the object is created from the request.
If the data violates the constraints, the normal method call does not continue.
Validation does not replace business rules
Format checks and simple constraints fit the web boundary well: whether a field is required, an email format, or a numeric range. Rules such as “a user with this email already exists” usually require access to application state and remain part of business logic.