Master Spring Boot 3 Parameter Validation with Real‑World Code Examples
This article introduces annotation‑based parameter validation in Spring Boot 3, explains built‑in constraints, shows how to use @Valid and @Validated in controllers, and provides multiple practical code snippets—including record types, error handling, collection validation, and return‑value checks—along with screenshots of validation errors.
Introduction
Annotation‑based parameter validation in Spring Boot offers a concise, declarative way to enforce constraints such as @NotNull , @NotBlank , @NotEmpty , @Size , @Pattern , @Email , etc., on entity fields. Adding @Valid or @Validated to a controller method triggers automatic validation and throws an exception when a rule is violated.
Practical Examples
1. Simple Record Validation
<code>public static record User(@NotEmpty(message = "姓名不能为空") String name, Integer age) {}</code>Using the record as a request body and annotating the controller method with @Valid :
<code>@PostMapping("")
public ResponseEntity<?> save(@Valid @RequestBody User user) {
// ...
}</code>When validation fails Spring returns an error response:
2. Handling Validation Errors with Errors
<code>@PostMapping("")
public ResponseEntity<?> save(@Valid @RequestBody User user, Errors errors) {
if (errors.hasErrors()) {
System.err.println(errors.getAllErrors());
}
return ResponseEntity.ok(user);
}</code>If validation fails the following error information is shown:
3. Parameter Validation with @Constraint
<code>@PostMapping("")
public ResponseEntity<?> save(@NotEmpty String name) {
// ...
}</code>Missing @Validated on the controller class causes a HandlerMethodValidationException :
4. Validating Collections with @Valid
<code>@PostMapping("")
public ResponseEntity<?> save(@Valid @RequestBody List<User> users) {
// ...
}</code>When validation fails the error screenshot appears:
Note: if an Errors parameter is present, the exception is not thrown.
5. Generic Collection Validation with @Valid on Elements
<code>@PostMapping("")
public ResponseEntity<?> save(@RequestBody List<@Valid User> users) {
// ...
}</code>Validation error screenshot:
6. Map Validation with @Valid Values
<code>@PostMapping("")
public ResponseEntity<?> save(@RequestBody Map<String, @Valid User> users) {
// ...
}</code>7. Method‑Level Validation (Class‑Level @Validated )
<code>@RestController
@RequestMapping("/api")
@Validated
public class ApiController {
@PostMapping("/save")
public ResponseEntity<?> save(@NotEmpty String name) {
// ...
}
}</code>When the parameter violates the constraint, a ConstraintViolationException is raised and the following image is produced:
8. Return‑Value Validation
<code>@GetMapping("/{id}")
@Valid
public User queryById(@PathVariable Long id) {
return new User(null, 0);
}</code>Alternatively:
<code>public @Valid User queryById(@PathVariable Long id) {
// ...
}</code>Invalid return values trigger the same error screenshot:
Promotional Note
The author also offers a continuously updated Spring Boot 3 case collection (over 100 practical articles) and a PDF e‑book that includes all source code. Subscribers receive the e‑book and source files for free.
Spring Full-Stack Practical Cases
Full-stack Java development with Vue 2/3 front-end suite; hands-on examples and source code analysis for Spring, Spring Boot 2/3, and Spring Cloud.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.