Sub topic 13
Validating beyond the controller
This chapter assumes you can already validate a request body with @Valid and handle MethodArgumentNotValidException in a @RestControllerAdvice. You also need to know what a Spring bean is.
Why the controller is not the only boundary
Controller validation only protects code reached through HTTP. Other callers can reach your service layer too:
- A message listener or scheduled job.
- A batch import that reads a CSV file.
- Another service in the same application.
If the rules live only on the controller, each of these callers can pass invalid data. Validating in the service layer puts the rule next to the logic that depends on it.
Method validation with @Validated
Put @Validated on a Spring bean and constraints on its method parameters. Spring Boot's validation starter registers a post-processor that wraps the bean in a proxy. The proxy checks the constraints before each call.
import jakarta.validation.Valid;
import jakarta.validation.constraints.Positive;
import org.springframework.stereotype.Service;
import org.springframework.validation.annotation.Validated;
@Service
@Validated
public class UserService {
public void register(@Valid CreateUserRequest request) {
// request is valid here, whoever called this method
}
public void deactivate(@Positive long userId) {
// userId is greater than zero here
}
}@Valid on request cascades into the DTO's own constraints. @Positive checks the primitive directly. A failure throws jakarta.validation.ConstraintViolationException. This is the same exception type that path variable validation raises.
Calling the Validator directly
Sometimes you want to validate an object at a specific point, such as each row of an import. Inject jakarta.validation.Validator and call it yourself.
import jakarta.validation.ConstraintViolation;
import jakarta.validation.ConstraintViolationException;
import jakarta.validation.Validator;
import java.util.Set;
import org.springframework.stereotype.Component;
@Component
public class UserImporter {
private final Validator validator;
public UserImporter(Validator validator) {
this.validator = validator;
}
public void importUser(CreateUserRequest request) {
Set<ConstraintViolation<CreateUserRequest>> violations = validator.validate(request);
if (!violations.isEmpty()) {
throw new ConstraintViolationException(violations);
}
// save the user
}
}This approach works without a proxy. It also lets you collect violations per row and keep going instead of stopping at the first bad one.
Gotchas
- The proxy must be used. A method that calls another method on
thisskips the proxy, so its constraints are not checked. Put validated methods on a bean that other beans call. - Class-level
@Validatedis required. Constraints on a service method's parameters do nothing without it. - Proxy limits apply. Private methods cannot be intercepted. Final classes and final methods cause problems for class-based proxies.
- Repeat constraints in overrides carefully. If a service implements an interface, Bean Validation forbids adding stricter parameter constraints in the implementing class than the interface declares. Declare the constraints on the interface, or on the class if there is no interface.
Handling the exception
Decide what a ConstraintViolationException means in your application. If it comes from a request that already passed controller validation, the service has found a bug or an unexpected caller. A 500 response is often the honest answer there. If the controller passes raw path or query values straight to a validated service, a 400 is correct.
import java.util.LinkedHashMap;
import java.util.Map;
import jakarta.validation.ConstraintViolationException;
import org.springframework.http.HttpStatus;
import org.springframework.http.ProblemDetail;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
@RestControllerAdvice
public class ConstraintViolationHandler {
@ExceptionHandler(ConstraintViolationException.class)
public ProblemDetail handle(ConstraintViolationException ex) {
ProblemDetail problem =
ProblemDetail.forStatusAndDetail(HttpStatus.BAD_REQUEST, "Validation failed");
Map<String, String> errors = new LinkedHashMap<>();
ex.getConstraintViolations().forEach(v ->
errors.putIfAbsent(v.getPropertyPath().toString(), v.getMessage()));
problem.setProperty("errors", errors);
return problem;
}
}Property paths from method validation look like register.request.email, which includes the method and parameter names. Trim them if you do not want to expose internals to clients.
Exercise
A @Validated service has two methods, a(@Positive long id) and b(long id). Method b calls this.a(id) with a negative number. Does validation fail, and why?
Show answer
No. The call goes through this, not through the Spring proxy, so the constraint on a is never checked. Move a to another bean, or inject that bean and call it through the injected reference.