Validationmedium0-2 years

How does @Valid on a request body actually trigger validation, and why does a @RequestParam need @Validated instead?

@Valid on a @RequestBody parameter tells Spring's argument resolver to run Bean Validation (JSR 380) on the bound object right after binding it, before your controller method runs — a failure throws MethodArgumentNotValidException. A @RequestParam or @PathVariable has no body to bind, so nothing in that path ever looks at a constraint annotation on it; validating those needs @Validated on the class, which wraps the bean in a proxy that intercepts the method call and validates via AOP, throwing a different exception, ConstraintViolationException.

The lesson behind it →