Sub topic 13
Validating beyond the controller
This chapter assumes you can already validate a request body with @Valid, handle MethodArgumentNotValidException in a @RestControllerAdvice, and use @Validated on a controller. You should also know basic Spring dependency injection and how Spring proxies work at a high level.
Controller validation checks the shape of an HTTP request. It does not cover the other places data enters your code: scheduled jobs, message listeners, imports, other services, or the database. This chapter shows how to reuse Bean Validation in those places, which rules do not belong in annotations, and which errors to expect.
What the controller cannot see
A @Valid request body protects one entry point. The same service method may also be called from a Kafka listener or a CSV import, and none of those callers pass through the controller. If the service assumes "the controller already checked", every new caller must repeat the checks, and one will forget.
Rules also differ in kind:
- Format rules need only the value itself, such as "not blank", "valid email", or "at least 18". Bean Validation handles these well.
- State rules need data from elsewhere, such as "this email is not already registered" or "the account has enough balance". They belong in service code and fail with domain exceptions.
Keep the two apart. A uniqueness check written as a custom constraint that queries the database runs on every validation, including in tests that construct DTOs. It also gives a false sense of safety, as the race condition section below explains.
The diagram shows where each kind of check sits.
Method validation in a service
Spring Boot registers a MethodValidationPostProcessor when the validation starter is on the classpath. It wraps any bean whose class is annotated @Validated in a proxy. The proxy validates arguments before the method runs, and it can validate return values too.
The service below registers a user. The repository is an in-memory stand-in for a real database, so the example runs without extra setup. The UNIQUE behavior is imitated by putIfAbsent.
package com.example.users;
import jakarta.validation.Valid;
import org.springframework.stereotype.Service;
import org.springframework.validation.annotation.Validated;
@Service
@Validated
public class UserService {
private final UserRepository users;
public UserService(UserRepository users) {
this.users = users;
}
public long register(@Valid CreateUserRequest request) {
if (users.existsByEmail(request.email())) {
throw new EmailAlreadyUsedException(request.email());
}
return users.save(request);
}
}package com.example.users;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.atomic.AtomicLong;
import org.springframework.stereotype.Repository;
public interface UserRepository {
boolean existsByEmail(String email);
long save(CreateUserRequest request);
}
@Repository
class InMemoryUserRepository implements UserRepository {
private final Map<String, Long> byEmail = new ConcurrentHashMap<>();
private final AtomicLong sequence = new AtomicLong();
@Override
public boolean existsByEmail(String email) {
return byEmail.containsKey(email);
}
@Override
public long save(CreateUserRequest request) {
long id = sequence.incrementAndGet();
if (byEmail.putIfAbsent(request.email(), id) != null) {
throw new EmailAlreadyUsedException(request.email());
}
return id;
}
}@Valid on the parameter tells the proxy to validate the record's own constraints. A constraint written directly on a parameter, such as @Min(1) long id, is checked without @Valid. On failure the proxy throws jakarta.validation.ConstraintViolationException, not MethodArgumentNotValidException. The exception is a plain runtime exception that carries a set of ConstraintViolation objects.
When the proxy does not apply
Method validation relies on a Spring proxy, so it fails silently in these cases:
- Self-invocation. If
registercalls another method of the same class throughthis, the call skips the proxy and the second method's constraints are not checked. - Objects you create with
new. Only beans managed by Spring are wrapped. - Final classes and methods, and private methods. The proxy cannot override them, so validation does not run.
- Missing
@Validated.@Validon a service parameter does nothing unless the class is annotated@Validated.
Constraint annotations on interface methods and their overrides must follow the Bean Validation rule that an overriding method may not add parameter constraints. If you see a ConstraintDeclarationException, this rule is the usual cause.
Controllers in Spring 6.1 and later
Since Spring Framework 6.1 (Spring Boot 3.2), controllers have built-in method validation. If a controller method has constraint annotations on its parameters and the class is not annotated @Validated, Spring validates them itself and throws HandlerMethodValidationException. If the class has @Validated, the AOP proxy handles it and you get ConstraintViolationException instead. Pick one style per project, and register a handler for the exception type you actually get.
Validating programmatically
Sometimes there is no method boundary to hang annotations on. Examples are a batch import that should collect every error instead of stopping at the first bad row, or a rule set chosen at runtime. Inject jakarta.validation.Validator, which Spring Boot provides as a bean.
package com.example.users;
import jakarta.validation.ConstraintViolation;
import jakarta.validation.Validator;
import java.util.List;
import java.util.Set;
import org.springframework.stereotype.Component;
@Component
public class ImportChecker {
private final Validator validator;
public ImportChecker(Validator validator) {
this.validator = validator;
}
public List<String> check(CreateUserRequest request) {
Set<ConstraintViolation<CreateUserRequest>> violations = validator.validate(request);
return violations.stream()
.map(v -> v.getPropertyPath() + ": " + v.getMessage())
.sorted()
.toList();
}
}validate returns the violations as a set and never throws, so you decide what to do with them. The set has no guaranteed order, which is why the code sorts the messages. This is also the way to apply a validation group in code: validator.validate(request, OnCreate.class).
Business rules and domain exceptions
Uniqueness and similar state rules belong in service code. They throw a domain exception that a controller advice maps to the right status.
package com.example.users;
import org.springframework.http.HttpStatus;
import org.springframework.http.ProblemDetail;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
public class EmailAlreadyUsedException extends RuntimeException {
public EmailAlreadyUsedException(String email) {
super("Email already registered: " + email);
}
}
@RestControllerAdvice
class DomainExceptionHandler {
@ExceptionHandler(EmailAlreadyUsedException.class)
public ProblemDetail handleConflict(EmailAlreadyUsedException ex) {
return ProblemDetail.forStatusAndDetail(HttpStatus.CONFLICT, "Email is already registered");
}
}The response says 409 Conflict, not 400. The request was well formed, but it conflicts with the current state. The handler returns a fixed message instead of ex.getMessage(), so the response does not echo the address back.
The race condition
existsByEmail followed by save is two steps. Two concurrent requests can both pass the check, and both then insert. The check gives a friendly error in the common case, but only a unique index in the database guarantees the rule. In the sample repository, putIfAbsent plays that role. With Spring Data JPA, the equivalent is a @Column(unique = true) or a unique index, plus a catch for DataIntegrityViolationException that you translate into the same EmailAlreadyUsedException.
Constraints on JPA entities
Hibernate runs Bean Validation on entities automatically when a validator is on the classpath. It validates before an insert or update, using the jakarta.persistence.validation.mode setting. The default, auto, enables it, and none turns it off.
Know these behaviors:
- A violation throws
ConstraintViolationExceptionduring flush. That can happen at commit, so the exception may arrive wrapped, for example in aTransactionSystemException. - At that point the request is already deep in a transaction. Treat an entity violation as a bug in the service, not as user error. The body should have been rejected earlier.
- Hibernate can derive DDL from some constraints, such as
@NotNulland@Size(max = ...), when it generates the schema. Do not rely on this in production. Write explicit migrations withNOT NULL,UNIQUEandCHECKconstraints.
Choosing the status code for a service violation
A handler for ConstraintViolationException written for controller parameters will also catch violations thrown by the service proxy and return 400. Whether that is right depends on the origin of the bad value:
| Origin of the invalid value | Likely cause | Reasonable response |
|---|---|---|
| Path variable or query parameter on a `@Validated` controller | Client error | 400 with field details |
| Argument built from an already validated request body | Bug in your mapping code | 500, log the violations |
| Argument from a message or an import | Bad input from another system | Reject the message or row and report it |
| Entity violation on flush | Bug or missing earlier check | 500, log the violations |
If you cannot tell the cases apart in one handler, catch the exception where the origin is known, in the listener or the import loop, and handle it there.
Testing service validation
The test below checks that the proxy is active and that the domain rule works. It assumes spring-boot-starter-test and a @SpringBootApplication class in com.example.users or a parent package.
package com.example.users;
import static org.junit.jupiter.api.Assertions.assertThrows;
import jakarta.validation.ConstraintViolationException;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
@SpringBootTest
class UserServiceTest {
@Autowired
UserService service;
@Test
void rejectsInvalidRequest() {
var request = new CreateUserRequest("", "not-an-email", 10);
assertThrows(ConstraintViolationException.class, () -> service.register(request));
}
@Test
void rejectsDuplicateEmail() {
var request = new CreateUserRequest("Ana", "[email protected]", 30);
service.register(request);
assertThrows(EmailAlreadyUsedException.class, () -> service.register(request));
}
}If you build the service with new UserService(repo) in a plain unit test, there is no proxy and the first test fails. That is expected. Unit tests that skip Spring should call a Validator directly, and tests of the proxy behavior need a Spring context.
Summary of the decisions
- Validate format with annotations, at the controller and again on service methods that other callers can reach.
- Validate state with explicit code that throws domain exceptions, and back it with a database constraint.
- Use an injected
Validatorwhen you need to collect violations or choose groups at runtime. - Decide per origin whether a
ConstraintViolationExceptionis a client error (400) or a bug (500).
Exercise
A service class is annotated @Validated. Its public method importAll(List<CreateUserRequest> rows) loops over the rows and calls another method in the same class, importOne(@Valid CreateUserRequest row). Invalid rows are imported without any error. Why, and how can you fix it?
Show answer
The call importOne(...) goes through this, so it bypasses the Spring proxy that performs method validation. The @Valid on importOne is never evaluated. Fixes: move importOne into a separate Spring bean and inject it, or inject a jakarta.validation.Validator and call validator.validate(row) in the loop, which also lets you collect all violations instead of failing at the first.
Exercise
Your register method checks existsByEmail and then saves, and duplicates still appear under load. What guarantees uniqueness, and what should the service do when that guarantee triggers?
Show answer
A unique index or constraint in the database guarantees it, because two concurrent requests can both pass the existence check. When the insert fails (for example with DataIntegrityViolationException in Spring Data JPA), the service should translate the error into the domain exception EmailAlreadyUsedException, so the advice returns 409 Conflict.