Spring MVC can validate a request object and direct method parameters through different exception paths.
Spring MVC validation paths: object constraints and method parameters
One bad request can fail before the handler
The checked controller accepts a JSON receipt command with a nonblank note and a count query parameter of at least one. An empty note returns 400 on the object-validation path; count zero returns 400 on the method-validation path. Valid inputs reach the handler and return their expected values. The test supplies a validator explicitly to standalone MockMvc.
An @Valid request object and a direct @Min parameter do not necessarily raise the same exception type. A handler that catches only MethodArgumentNotValidException can leave HandlerMethodValidationException with a different public shape. The companion advice makes both return one bounded response. Nested objects need their own @Valid path and are covered separately in nested validation.
Validation is not authorization
A well-formed note and positive count say nothing about who may view or change a receipt. Authenticate, authorize and constrain persistence separately. Also bound raw request bytes and collections before expensive parsing; a field constraint does not protect the whole transport from oversized input.
Checked source
record ReceiptCommand(@NotBlank String note) {}
@PostMapping(path = "/contract/validated-receipts", consumes = "application/json")
String create(@Valid @RequestBody ReceiptCommand command) { return command.note(); }
@GetMapping("/contract/receipt-limit")
String limit(@RequestParam @Min(1) int count) { return Integer.toString(count); }Verification boundary
MvcValidationModesTest.objectAndDirectParameterConstraintsRejectDifferentInputs runs in the downloadable Spring source kit. The excerpt omits imports and surrounding setup; the kit contains the complete tests.
Costs and limits
Constraint evaluation is small in this fixture, but validation cost depends on input size and custom validators. Standalone MockMvc checks local MVC mapping and validator behavior, not authentication, deployment request limits or the full application's advice registration.
Common Mistakes
- Do not handle only one validation exception shape when a method has direct constraints.
- Do not assume @Valid by itself bounds raw request size.
- Do not treat a valid request body as an authorized operation.
Read next
Spring MVC request validation: reject invalid commands before mutation, Spring MVC nested validation: reject a bad line before the handler, Spring MVC validation errors: one public ProblemDetail for two failure paths.
