Jakarta Bean Validation in Spring controllers and services
Follow request, object, and method validation in Spring Boot, then implement Jakarta Validation groups and a custom ConstraintValidator.
Bean Validation lets me put a constraint beside the data it describes. In Spring, I also need to know who triggers validation, because request-body binding and service-method interception take different paths.
The examples use Spring Boot 3.x, Jakarta Validation 3.0, and Hibernate Validator 8.x.
The standard and its provider
Repeated null and blank checks distract from the rules a controller or service is meant to enforce. Jakarta Validation defines annotations such as @NotBlank and @Email, as well as the APIs for applying them. A provider evaluates the constraints. The Boot validation starter brings in Hibernate Validator and integrates it with Spring.
| Version | Package | Addition |
|---|---|---|
| JSR 303, Bean Validation 1.0 | javax.validation | Bean property constraints |
| JSR 349, Bean Validation 1.1 | javax.validation | Parameter and return-value validation, plus CDI integration |
| JSR 380, Bean Validation 2.0 | javax.validation | Java 8 types and constraints on container elements |
| Jakarta Validation 3.x | jakarta.validation | Jakarta namespace used by Spring Boot 3.x |
Container-element constraints let you express List<@NotBlank String> directly. The validator can check each list element using the same constraint as it uses for an ordinary field.
flowchart TD
APP["Request and model constraints"] --> API["Jakarta Validation API"]
API --> HV["Hibernate Validator"]
BOOT["Spring Boot configuration"] --> HV
Boot’s web starter no longer includes the validation starter by default. Add it as an explicit dependency.
1
2
3
4
5
6
// build.gradle
dependencies {
implementation 'org.springframework.boot:spring-boot-starter-web'
// Includes Jakarta Validation API and Hibernate Validator
implementation 'org.springframework.boot:spring-boot-starter-validation'
}
Request bodies and service methods
For a typical @RequestBody @Valid parameter, RequestResponseBodyMethodProcessor reads the body and validates the bound request object. With no adjacent BindingResult handling the error, a failed constraint can produce MethodArgumentNotValidException. This is the path behind the usual HTTP 400 response for an invalid body.
For a service with class-level @Validated, Spring can apply validation through an AOP proxy and MethodValidationInterceptor. That path checks method parameters and return values. It typically raises ConstraintViolationException with default interceptor settings. A call made directly inside the same instance can bypass the proxy.
flowchart TD
HTTP["HTTP request"] --> BODY["MVC binds and validates the body"]
BODY --> BODYFAIL["MethodArgumentNotValidException"]
CALL["Call a validated service bean"] --> PROXY["MethodValidationInterceptor"]
PROXY --> METHODFAIL["ConstraintViolationException"]
| Question | Jakarta @Valid | Spring @Validated |
|---|---|---|
| Main role | Trigger validation where supported and cascade into nested objects | Select groups or qualify a bean for proxy-based method validation |
| Nested field | Add @Valid to the field or element | Use @Valid for cascading |
| Groups | The caller or entry point selects groups | Pass the groups to @Validated |
| Typical MVC body failure | MethodArgumentNotValidException | Same exception when applied to a body parameter |
| Service method failure | Cascades when executable validation runs | Usually ConstraintViolationException through the proxy |
Spring MVC has a separate built-in method-validation path in Spring Framework 6.1 and later. It can raise
HandlerMethodValidationExceptionfor controller parameter constraints. When setting up@RestControllerAdvice, verify which path each endpoint actually uses.
Cascading and validation groups
Suppose a create request must omit the reservation ID, while an update must supply it. The example uses marker interfaces to activate the right set of constraints. Add @Valid wherever validation should descend into another object.
1
2
3
4
5
6
7
// src/main/java/com/example/reservation/dto/ReservationGroups.java
package com.example.reservation.dto;
public interface ReservationGroups {
interface Create {}
interface Update {}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
// src/main/java/com/example/reservation/dto/ReservationRequest.java
package com.example.reservation.dto;
import jakarta.validation.Valid;
import jakarta.validation.constraints.NotBlank;
import jakarta.validation.constraints.NotNull;
import jakarta.validation.constraints.Null;
import jakarta.validation.constraints.Positive;
public record ReservationRequest(
@Null(groups = ReservationGroups.Create.class, message = "Omit the ID when creating a reservation.")
@NotNull(groups = ReservationGroups.Update.class, message = "An ID is required when updating a reservation.")
Long reservationId,
@NotBlank(groups = {ReservationGroups.Create.class, ReservationGroups.Update.class})
String roomCode,
@Positive(groups = {ReservationGroups.Create.class, ReservationGroups.Update.class})
int attendeeCount,
@Valid // Use @Valid to cascade into the nested object.
@NotNull(groups = {ReservationGroups.Create.class, ReservationGroups.Update.class})
HostInfo host
) {
public record HostInfo(
@NotBlank(groups = {ReservationGroups.Create.class, ReservationGroups.Update.class})
String hostName
) {}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
// src/main/java/com/example/reservation/controller/ReservationController.java
package com.example.reservation.controller;
import com.example.reservation.dto.ReservationGroups;
import com.example.reservation.dto.ReservationRequest;
import org.springframework.http.ResponseEntity;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
@RestController
@RequestMapping("/api/reservations")
public class ReservationController {
@PostMapping
public ResponseEntity<String> create(
@Validated(ReservationGroups.Create.class) @RequestBody ReservationRequest request
) {
return ResponseEntity.ok("created: " + request.roomCode());
}
@PutMapping
public ResponseEntity<String> update(
@Validated(ReservationGroups.Update.class) @RequestBody ReservationRequest request
) {
return ResponseEntity.ok("updated: " + request.reservationId());
}
}
If a property constraint belongs to the default group, include that group when you want it to run alongside the operation-specific constraints, or declare its group membership explicitly. I check this with one test per operation. Once a DTO starts to accumulate several groups and conflicting rules, two request types often communicate the API more clearly.
A reusable constraint for room codes
The required format is ROOM- followed by three digits. Jakarta Validation needs message, groups, and payload members on a constraint annotation. A ConstraintValidator implements the rule for the supported value type.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
// src/main/java/com/example/reservation/validation/RoomCode.java
package com.example.reservation.validation;
import jakarta.validation.Constraint;
import jakarta.validation.Payload;
import java.lang.annotation.*;
@Documented
@Constraint(validatedBy = RoomCodeValidator.class)
@Target({ElementType.FIELD, ElementType.PARAMETER})
@Retention(RetentionPolicy.RUNTIME)
public @interface RoomCode {
String message() default "Room codes must use the 'ROOM-000' format.";
Class<?>[] groups() default {};
Class<? extends Payload>[] payload() default {};
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
// src/main/java/com/example/reservation/validation/RoomCodeValidator.java
package com.example.reservation.validation;
import jakarta.validation.ConstraintValidator;
import jakarta.validation.ConstraintValidatorContext;
import java.util.regex.Pattern;
public class RoomCodeValidator implements ConstraintValidator<RoomCode, String> {
private static final Pattern ROOM_CODE_PATTERN = Pattern.compile("^ROOM-\\d{3}$");
@Override
public boolean isValid(String value, ConstraintValidatorContext context) {
if (value == null) {
return true; // Let @NotNull or @NotBlank enforce presence
}
return ROOM_CODE_PATTERN.matcher(value).matches();
}
}
The validator accepts null so a separate @NotNull or @NotBlank can decide whether the field is required. Spring’s LocalValidatorFactoryBean can build validators with injected dependencies. I keep database lookups in the service when a rule needs a transaction, an authorization decision, or a current view of persistent data.
Verifying which path caught the problem
Send a bad body through MVC, then call an invalid service method through the Spring proxy. Assert the exception that the application actually receives and the response it maps that exception to. For the reservation example, check that create rejects an ID, update requires one, and nested input reports violations on its field path. Test the room code validator separately with a valid format, an invalid format, and null.