Spring Validation: declaring rules once and checking them everywhere

Bean Validation lets you write rules such as "not blank" or "at least 1" as annotations on fields and parameters, and check them with one call. Spring connects it to beans and controllers, so invalid input is rejected before your code runs. This page shows how the validator reads the rules, where @Valid and @Validated are needed, and the cases where validation silently does nothing.

Contents

How Bean Validation works in Spring

Input checks written by hand, such as if (name == null || name.isBlank()), end up repeated in controllers, services and batch jobs, and they drift apart. Jakarta Bean Validation turns each rule into an annotation on a field, record component or parameter. A validator reads those annotations by reflection, checks the values, and returns every broken rule at once as a set of ConstraintViolation objects.

Three layers are involved:

  • Jakarta Validation API: the annotations (@NotBlank, @Size, @Email) and interfaces (Validator, ConstraintValidator), in the jakarta.validation package. Version 3.1 is current.
  • Hibernate Validator: the implementation that does the checking. Spring Boot 4.1's spring-boot-starter-validation brings Hibernate Validator 9.1 and an expression language library for message templates.
  • Spring's integration: LocalValidatorFactoryBean exposes the validator as a bean, MethodValidationPostProcessor checks parameters and return values of bean methods through a proxy, and Spring MVC validates request bodies and parameters before calling a controller.

Two annotations trigger validation, and they are not interchangeable:

@Valid and @Validated
AnnotationFromWhere it goesWhat it does
@ValidJakarta ValidationFields, parameters, return values, container elementsValidate this object too: cascade into its own constraints
@ValidatedSpringA bean class, or a controller parameterOn a class: switch on method validation for the bean. On a parameter: validate with the listed groups

The built-in constraints cover most needs:

Common built-in constraints
ConstraintChecksAccepts null
@NotNullValue is not nullNo
@NotEmptyNot null, and length or size above 0No
@NotBlankNot null, and at least one non-whitespace characterNo
@Size(min, max)Length of a string, size of a collection, map or arrayYes
@Min, @Max, @Positive, @PositiveOrZeroNumeric boundsYes
@Email, @Pattern(regexp)String formatYes
@Past, @Future, @PastOrPresentDates and times relative to nowYes
@NullValue is nullOnly null

The "accepts null" column is the most important part of this table. Every constraint except the null checks treats null as valid, so that each annotation checks one thing and they can be combined. A field that must be present and well-formed needs both, for example @NotNull @Email. The programs on this page use Spring Framework 7.0 and Hibernate Validator 9.1.5; the last one is a Spring Boot 4.1 web application.

Validating an object directly

The simplest use needs no annotations on beans at all: build a validator and pass it an object. The three signups below are chosen to show a valid object, one that breaks four rules, and one made of nulls, which reveals which constraints accept null:

Java
import jakarta.validation.ConstraintViolation;
import jakarta.validation.Validator;
import jakarta.validation.constraints.Email;
import jakarta.validation.constraints.Max;
import jakarta.validation.constraints.Min;
import jakarta.validation.constraints.NotBlank;
import jakarta.validation.constraints.NotNull;
import jakarta.validation.constraints.Size;
import java.util.Comparator;
import java.util.Locale;
import java.util.Set;
import org.springframework.validation.beanvalidation.LocalValidatorFactoryBean;

public class ValidateObject {

    record Signup(
            @NotBlank String username,
            @Email @NotNull String email,
            @Size(min = 8, max = 64) String password,
            @Min(13) @Max(120) int age) {
    }

    static void check(Validator validator, Signup signup) {
        Set<ConstraintViolation<Signup>> violations = validator.validate(signup);
        System.out.println(signup);
        System.out.println("  " + violations.size() + " violation(s)");
        violations.stream()
                .sorted(Comparator.comparing((ConstraintViolation<Signup> v) ->
                        v.getPropertyPath().toString()))
                .forEach(v -> System.out.println("  " + v.getPropertyPath() + " = "
                        + v.getInvalidValue() + ": " + v.getMessage()));
    }

    public static void main(String[] args) {
        Locale.setDefault(Locale.ENGLISH);
        try (var factory = new LocalValidatorFactoryBean()) {
            factory.afterPropertiesSet();
            Validator validator = factory.getValidator();
            check(validator, new Signup("ann", "ann@example.com", "correct-horse", 30));
            check(validator, new Signup("  ", "not-an-email", "short", 9));
            check(validator, new Signup(null, null, null, 30));
        }
    }
}
Output
Signup[username=ann, email=ann@example.com, password=correct-horse, age=30]
  0 violation(s)
Signup[username=  , email=not-an-email, password=short, age=9]
  4 violation(s)
  age = 9: must be greater than or equal to 13
  email = not-an-email: must be a well-formed email address
  password = short: size must be between 8 and 64
  username =   : must not be blank
Signup[username=null, email=null, password=null, age=30]
  2 violation(s)
  email = null: must not be null
  username = null: must not be blank
  • The first signup has 0 violations, so validate returned an empty set.
  • The second broke all four rules at once, and each violation carries the property path, the invalid value and a message such as size must be between 8 and 64. The validator does not stop at the first failure, which is what a form needs to show every error together.
  • The third had 3 null fields but only 2 violations. password is null and has only @Size, which accepts null, so a missing password passed. email failed only @NotNull, not @Email.
  • The set has no defined order, so the program sorts it by property path to give stable output.

The messages come from Hibernate Validator's built-in resource bundle, in the default locale; this program sets English so that the output does not depend on the machine. A template such as {jakarta.validation.constraints.Size.message} resolves to size must be between {min} and {max}, and the attribute values are filled in. In a Spring application, LocalValidatorFactoryBean can use the application's MessageSource, so you can override any message in messages.properties.

Nested objects and collections: @Valid cascades

Constraints on a nested object are not checked unless the field that holds it asks for it. An order with a broken address and a broken line item shows the difference, because the same data is valid or invalid depending on one annotation:

Java
import jakarta.validation.ConstraintViolation;
import jakarta.validation.Valid;
import jakarta.validation.Validation;
import jakarta.validation.Validator;
import jakarta.validation.ValidatorFactory;
import jakarta.validation.constraints.NotBlank;
import jakarta.validation.constraints.NotEmpty;
import jakarta.validation.constraints.Positive;
import java.util.List;
import java.util.Locale;
import java.util.Set;

public class CascadeValidation {

    record Address(@NotBlank String city, @NotBlank String postcode) {
    }

    record Line(@NotBlank String sku, @Positive int quantity) {
    }

    record OrderWithoutValid(Address shipTo, List<Line> lines) {
    }

    record Order(
            @Valid Address shipTo,
            @NotEmpty List<@Valid Line> lines,
            List<@NotBlank String> couponCodes) {
    }

    static void print(String label, Set<? extends ConstraintViolation<?>> found) {
        System.out.println(label + ": " + found.size() + " violation(s)");
        found.stream()
                .map(v -> "  " + v.getPropertyPath() + ": " + v.getMessage())
                .sorted()
                .forEach(System.out::println);
    }

    public static void main(String[] args) {
        Locale.setDefault(Locale.ENGLISH);
        try (ValidatorFactory factory = Validation.buildDefaultValidatorFactory()) {
            Validator validator = factory.getValidator();
            Address badAddress = new Address("", "");
            List<Line> badLines = List.of(new Line("A-1", 2), new Line("", 0));

            print("Without @Valid",
                    validator.validate(new OrderWithoutValid(badAddress, badLines)));
            print("With @Valid",
                    validator.validate(new Order(badAddress, badLines, List.of("SAVE10", " "))));
            print("Empty order",
                    validator.validate(new Order(new Address("Leeds", "LS1"), List.of(), null)));
        }
    }
}
Output
Without @Valid: 0 violation(s)
With @Valid: 5 violation(s)
  couponCodes[1].<list element>: must not be blank
  lines[1].quantity: must be greater than 0
  lines[1].sku: must not be blank
  shipTo.city: must not be blank
  shipTo.postcode: must not be blank
Empty order: 1 violation(s)
  lines: must not be empty
  • Without @Valid, the order had 0 violations, although its address has two blank fields and one line has a blank SKU and a quantity of 0. The validator checked only constraints on OrderWithoutValid itself, and it has none.
  • With @Valid on shipTo and on the element type List<@Valid Line>, it found 5. The paths show where: shipTo.city, lines[1].sku, lines[1].quantity.
  • List<@NotBlank String> is a container element constraint: it checks each string in the list, and the path couponCodes[1].<list element> points to the blank second code.
  • An empty list passes @Valid, because there is nothing to cascade into. @NotEmpty on the list caught it.

Forgetting @Valid on a nested field is the most common validation bug, because nothing fails: the outer object validates, and the inner one is never looked at. Every field whose type has its own constraints needs it.

Method validation on Spring beans

Constraints can also go on method parameters and return values, so a service rejects bad calls whoever the caller is. Spring checks them in a proxy created by MethodValidationPostProcessor, and only for beans whose class carries @Validated. This program calls the same method on a bean with and without that annotation:

Java
import jakarta.validation.ConstraintViolationException;
import jakarta.validation.Valid;
import jakarta.validation.constraints.Email;
import jakarta.validation.constraints.Min;
import jakarta.validation.constraints.NotBlank;
import jakarta.validation.constraints.NotNull;
import java.util.Locale;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.validation.annotation.Validated;
import org.springframework.validation.beanvalidation.MethodValidationPostProcessor;

public class MethodValidation {

    record Customer(@NotBlank String name, @Email String email) {
    }

    @Validated
    static class CustomerService {
        public String register(@Valid Customer customer) {
            return "registered " + customer.name();
        }

        public String page(@Min(1) int page, @NotBlank String sort) {
            return "page " + page + " sorted by " + sort;
        }

        public @NotNull String nickname(String name) {
            return name.equals("ann") ? "annie" : null;
        }
    }

    static class UnannotatedService {
        public String register(@Valid Customer customer) {
            return "registered " + customer.name();
        }
    }

    @Configuration
    static class Config {
        @Bean
        static MethodValidationPostProcessor methodValidationPostProcessor() {
            return new MethodValidationPostProcessor();
        }

        @Bean
        CustomerService customerService() {
            return new CustomerService();
        }

        @Bean
        UnannotatedService unannotatedService() {
            return new UnannotatedService();
        }
    }

    interface Call {
        String run();
    }

    static void attempt(String label, Call call) {
        System.out.println(label);
        try {
            System.out.println("  returned: " + call.run());
        } catch (ConstraintViolationException e) {
            e.getConstraintViolations().stream()
                    .map(v -> "  violation: " + v.getPropertyPath() + " " + v.getMessage())
                    .sorted()
                    .forEach(System.out::println);
        }
    }

    public static void main(String[] args) {
        Locale.setDefault(Locale.ENGLISH);
        try (var context = new AnnotationConfigApplicationContext(Config.class)) {
            CustomerService service = context.getBean(CustomerService.class);
            Customer bad = new Customer("", "nope");
            attempt("register(bad customer):", () -> service.register(bad));
            attempt("page(0, \"\"):", () -> service.page(0, ""));
            attempt("nickname(\"bob\"), return value checked:", () -> service.nickname("bob"));
            attempt("Same call on a bean without @Validated:",
                    () -> context.getBean(UnannotatedService.class).register(bad));
        }
    }
}
Output
register(bad customer):
  violation: register.customer.email must be a well-formed email address
  violation: register.customer.name must not be blank
page(0, ""):
  violation: page.page must be greater than or equal to 1
  violation: page.sort must not be blank
nickname("bob"), return value checked:
  violation: nickname.<return value> must not be null
Same call on a bean without @Validated:
  returned: registered
  • register threw ConstraintViolationException before its body ran. The paths name the method, the parameter and the field: register.customer.email.
  • page(0, "") broke the constraints written directly on the two parameters, @Min(1) and @NotBlank; no wrapper object is needed.
  • nickname("bob") ran, returned null, and then failed: @NotNull on the return type is checked after the method returns, at nickname.<return value>.
  • On UnannotatedService, the identical register call returned normally with an invalid customer. Its @Valid was ignored, because without @Validated on the class the bean gets no validation proxy.

Parameter names such as customer and page come from the class file, which contains them only when the code is compiled with javac -parameters. The programs on this page are compiled that way, as Spring Boot's Maven and Gradle plugins do by default; without the flag the paths read register.arg0.email. Spring Boot registers MethodValidationPostProcessor automatically. In plain Spring, declare it as a static bean method, as here, because it is a post-processor that must exist before other beans are created. Since it works through a proxy, it has the same limits as other Spring proxies: a call on this is not validated, as the Spring AOP page explains.

Validation groups

The same class often has different rules in different situations: a new product must not have an id yet, while an update must have one. Groups attach each constraint to one or more situations. The four runs below validate with different group lists, including the trap of leaving out Default:

Java
import jakarta.validation.Validation;
import jakarta.validation.Validator;
import jakarta.validation.ValidatorFactory;
import jakarta.validation.constraints.NotBlank;
import jakarta.validation.constraints.NotNull;
import jakarta.validation.constraints.Null;
import jakarta.validation.groups.Default;
import java.util.Locale;

public class ValidationGroups {

    interface OnCreate {
    }

    interface OnUpdate {
    }

    record Product(
            @Null(groups = OnCreate.class) @NotNull(groups = OnUpdate.class) Long id,
            @NotBlank String name) {
    }

    static void run(Validator validator, String label, Product product, Class<?>... groups) {
        var found = validator.validate(product, groups);
        System.out.println(label + " -> " + found.size() + " violation(s)");
        found.stream()
                .map(v -> "  " + v.getPropertyPath() + ": " + v.getMessage())
                .sorted()
                .forEach(System.out::println);
    }

    public static void main(String[] args) {
        Locale.setDefault(Locale.ENGLISH);
        try (ValidatorFactory factory = Validation.buildDefaultValidatorFactory()) {
            Validator v = factory.getValidator();
            Product newProduct = new Product(5L, "");
            Product update = new Product(null, "");

            run(v, "create, groups OnCreate", newProduct, OnCreate.class);
            run(v, "create, groups OnCreate + Default", newProduct, OnCreate.class,
                    Default.class);
            run(v, "update, groups OnUpdate + Default", update, OnUpdate.class, Default.class);
            run(v, "no groups (Default only)", update);
        }
    }
}
Output
create, groups OnCreate -> 1 violation(s)
  id: must be null
create, groups OnCreate + Default -> 2 violation(s)
  id: must be null
  name: must not be blank
update, groups OnUpdate + Default -> 2 violation(s)
  id: must not be null
  name: must not be blank
no groups (Default only) -> 1 violation(s)
  name: must not be blank
  • With only OnCreate, the validator reported id: must be null but not the blank name. @NotBlank on name has no groups attribute, so it belongs to Default, and Default was not requested.
  • With OnCreate and Default, both problems were reported, which is what a create endpoint wants.
  • With OnUpdate and Default, the update without an id failed @NotNull, and the name failed too.
  • With no groups, only Default ran: the group-specific id rules were skipped.

In Spring, pass groups with @Validated(OnCreate.class) on a controller parameter or on a service method. To avoid listing Default every time, a group interface can extend it: interface OnCreate extends Default {}. Many teams use separate request records for create and update instead, which keeps each class's rules visible in one place and needs no groups.

Custom constraints

When no built-in annotation fits, write a constraint: an annotation marked with @Constraint, and a ConstraintValidator that implements the check. The booking below has two custom rules, a format check on one field and a rule that compares two fields:

Java
import jakarta.validation.Constraint;
import jakarta.validation.ConstraintValidator;
import jakarta.validation.ConstraintValidatorContext;
import jakarta.validation.Payload;
import jakarta.validation.Validation;
import jakarta.validation.Validator;
import jakarta.validation.ValidatorFactory;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import java.time.LocalDate;
import java.util.Locale;

public class CustomConstraint {

    @Target({ElementType.FIELD, ElementType.PARAMETER, ElementType.RECORD_COMPONENT})
    @Retention(RetentionPolicy.RUNTIME)
    @Constraint(validatedBy = SkuValidator.class)
    @interface Sku {
        String message() default "must look like {prefix}-1234";
        String prefix() default "SKU";
        Class<?>[] groups() default {};
        Class<? extends Payload>[] payload() default {};
    }

    public static class SkuValidator implements ConstraintValidator<Sku, String> {
        private String prefix;

        @Override
        public void initialize(Sku annotation) {
            prefix = annotation.prefix();
        }

        @Override
        public boolean isValid(String value, ConstraintValidatorContext context) {
            if (value == null) {
                return true;            // leave null checks to @NotNull
            }
            return value.matches(prefix + "-\\d{4}");
        }
    }

    @Target(ElementType.TYPE)
    @Retention(RetentionPolicy.RUNTIME)
    @Constraint(validatedBy = DateRangeValidator.class)
    @interface ValidRange {
        String message() default "must not be before the start date";
        Class<?>[] groups() default {};
        Class<? extends Payload>[] payload() default {};
    }

    public static class DateRangeValidator implements ConstraintValidator<ValidRange, Booking> {
        @Override
        public boolean isValid(Booking booking, ConstraintValidatorContext context) {
            if (booking.from() == null || booking.to() == null
                    || !booking.to().isBefore(booking.from())) {
                return true;
            }
            context.disableDefaultConstraintViolation();
            String template = context.getDefaultConstraintMessageTemplate();
            context.buildConstraintViolationWithTemplate(template)
                    .addPropertyNode("to")
                    .addConstraintViolation();
            return false;
        }
    }

    @ValidRange
    record Booking(@Sku(prefix = "ROOM") String room, LocalDate from, LocalDate to) {
    }

    public static void main(String[] args) {
        Locale.setDefault(Locale.ENGLISH);
        try (ValidatorFactory factory = Validation.buildDefaultValidatorFactory()) {
            Validator validator = factory.getValidator();
            Booking[] bookings = {
                new Booking("ROOM-0042", LocalDate.of(2026, 5, 1), LocalDate.of(2026, 5, 4)),
                new Booking("SKU-0042", LocalDate.of(2026, 5, 1), LocalDate.of(2026, 5, 4)),
                new Booking("ROOM-7", LocalDate.of(2026, 5, 4), LocalDate.of(2026, 5, 1)),
            };
            for (Booking b : bookings) {
                System.out.println(b);
                validator.validate(b).stream()
                        .map(v -> "  " + v.getPropertyPath() + ": " + v.getMessage())
                        .sorted()
                        .forEach(System.out::println);
            }
        }
    }
}
Output
Booking[room=ROOM-0042, from=2026-05-01, to=2026-05-04]
Booking[room=SKU-0042, from=2026-05-01, to=2026-05-04]
  room: must look like ROOM-1234
Booking[room=ROOM-7, from=2026-05-04, to=2026-05-01]
  room: must look like ROOM-1234
  to: must not be before the start date
  • The first booking passed both rules.
  • SKU-0042 failed @Sku(prefix = "ROOM"). The message template must look like {prefix}-1234 was filled in with the annotation's own attribute, giving must look like ROOM-1234.
  • The third booking failed both. The date check is a class-level constraint, because it needs two fields; it reported its violation on the property to through buildConstraintViolationWithTemplate(...).addPropertyNode("to"), so a form can show the error next to that field instead of at the top.

Every constraint annotation must declare message, groups and payload, or the validator rejects it with a ConstraintDefinitionException. Return true for null unless the constraint is about null; that keeps it consistent with the built-in ones and lets @NotNull decide. In a Spring application, validator classes are created by Spring, so they can have other beans injected, for example a repository for a "username not taken" rule. Keep such checks rare: a database query inside validation runs on every call, and the answer can change before the data is saved.

Validation in a REST controller

In Spring MVC, validation happens before the controller method runs, and an invalid request becomes a 400 response. Request bodies and simple parameters fail with different exceptions, so this Spring Boot application sends one valid and one invalid request of each kind:

Java
package demo.validation.rest;

import jakarta.validation.Valid;
import jakarta.validation.constraints.Email;
import jakarta.validation.constraints.Max;
import jakarta.validation.constraints.Min;
import jakarta.validation.constraints.NotBlank;
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.util.Locale;
import java.util.Map;
import java.util.TreeMap;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Import;
import org.springframework.http.HttpStatus;
import org.springframework.http.ProblemDetail;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.method.annotation.HandlerMethodValidationException;

public class RestValidation {

    record NewUser(@NotBlank String name, @Email @NotBlank String email) {
    }

    @RestController
    static class UserController {
        @PostMapping("/users")
        String create(@Valid @RequestBody NewUser user) {
            return "created " + user.name();
        }

        @GetMapping("/users/{id}")
        String find(@PathVariable @Min(1) long id,
                    @RequestParam(defaultValue = "10") @Min(1) @Max(100) int size) {
            return "user " + id + ", page size " + size;
        }
    }

    @RestControllerAdvice
    static class ValidationErrors {
        @ExceptionHandler(MethodArgumentNotValidException.class)
        ProblemDetail body(MethodArgumentNotValidException e) {
            Map<String, String> errors = new TreeMap<>();
            e.getBindingResult().getFieldErrors()
                    .forEach(f -> errors.put(f.getField(), f.getDefaultMessage()));
            ProblemDetail problem = ProblemDetail.forStatusAndDetail(
                    HttpStatus.BAD_REQUEST, "request body is invalid");
            problem.setProperty("errors", errors);
            return problem;
        }

        @ExceptionHandler(HandlerMethodValidationException.class)
        ProblemDetail params(HandlerMethodValidationException e) {
            Map<String, String> errors = new TreeMap<>();
            e.getParameterValidationResults().forEach(r -> errors.put(
                    r.getMethodParameter().getParameterName(),
                    r.getResolvableErrors().get(0).getDefaultMessage()));
            ProblemDetail problem = ProblemDetail.forStatusAndDetail(
                    HttpStatus.BAD_REQUEST, "request parameters are invalid");
            problem.setProperty("errors", errors);
            return problem;
        }
    }

    @Configuration
    @EnableAutoConfiguration
    @Import({UserController.class, ValidationErrors.class})
    static class App {
    }

    static final HttpClient HTTP = HttpClient.newHttpClient();

    static void send(String label, HttpRequest request) throws Exception {
        HttpResponse<String> r = HTTP.send(request, HttpResponse.BodyHandlers.ofString());
        System.out.println(label);
        System.out.println("  " + r.statusCode() + " " + r.body());
    }

    public static void main(String[] args) throws Exception {
        Locale.setDefault(Locale.ENGLISH);
        SpringApplication app = new SpringApplication(App.class);
        app.setDefaultProperties(Map.of("server.port", "0", "spring.main.banner-mode", "off",
                "logging.level.root", "WARN"));
        try (ConfigurableApplicationContext context = app.run()) {
            String base = "http://localhost:"
                    + context.getEnvironment().getProperty("local.server.port");
            for (String json : new String[] {
                    "{\"name\":\"Ann\",\"email\":\"ann@example.com\"}",
                    "{\"name\":\"\",\"email\":\"not-an-email\"}"}) {
                send("POST /users " + json, HttpRequest.newBuilder(URI.create(base + "/users"))
                        .header("Content-Type", "application/json")
                        .POST(HttpRequest.BodyPublishers.ofString(json)).build());
            }
            for (String path : new String[] {"/users/7?size=20", "/users/0?size=500"}) {
                send("GET " + path,
                        HttpRequest.newBuilder(URI.create(base + path)).build());
            }
        }
    }
}
Output
POST /users {"name":"Ann","email":"ann@example.com"}
  200 created Ann
POST /users {"name":"","email":"not-an-email"}
  400 {"detail":"request body is invalid","instance":"/users","status":400,"title":"Bad Request","errors":{"email":"must be a well-formed email address","name":"must not be blank"}}
GET /users/7?size=20
  200 user 7, page size 20
GET /users/0?size=500
  400 {"detail":"request parameters are invalid","instance":"/users/0","status":400,"title":"Bad Request","errors":{"id":"must be greater than or equal to 1","size":"must be less than or equal to 100"}}
  • The valid body reached the controller, which returned created Ann.
  • The invalid body failed @Valid @RequestBody with MethodArgumentNotValidException. The handler collected the two field errors into a ProblemDetail, the RFC 9457 error format that Spring builds in, and the client received a 400 with "errors":{"email":...,"name":...}.
  • /users/0?size=500 broke @Min(1) on the path variable and @Max(100) on the request parameter. These constraints sit directly on the parameters, so Spring's built-in method validation, added in Spring Framework 6.1, raised HandlerMethodValidationException instead. Its results name both parameters, id and size.

Before Spring Framework 6.1, constraints on @PathVariable and @RequestParam worked only with @Validated on the controller class and produced a ConstraintViolationException, which became a 500 unless you handled it. Code written for Spring Boot 2 often still has that annotation; on Spring Boot 4 it is not needed for controllers. Without an @ExceptionHandler, both exceptions still give a 400, but Spring Boot's default error body names only the status and the path, not the fields that failed. The program sits in its own package because Spring Boot warns when @EnableAutoConfiguration is declared in the default package. For more on error responses, see exception handling in Spring Boot.

Choosing where to validate

Validation tools and when to use each
SituationUse
A JSON request body@Valid @RequestBody, with a handler for MethodArgumentNotValidException
Path variables and query parametersConstraints directly on the parameters; handle HandlerMethodValidationException
A service that must reject bad calls from any caller@Validated on the class, constraints on parameters and return values
Nested objects and lists of objects@Valid on the field, or on the element type: List<@Valid Line>
Different rules for create and updateSeparate request records, or groups with @Validated(OnCreate.class)
A rule that compares two fieldsA class-level custom constraint that reports on one property
A rule that needs the database, such as uniquenessA check in the service, backed by a unique constraint in the database
Validation outside Spring, such as a batch fileA Validator called directly

Validation guards the edges of the application, but it is not a substitute for database constraints, which still hold when two requests write at the same time. For the proxies behind method validation, see Spring AOP; for REST endpoints in general, see REST controllers in Spring Boot.