Backend Development 9 min read

Using @Validated in Spring Boot to Eliminate Repetitive Validation Code

This article explains how the @Validated annotation in Spring Boot can replace repetitive validation logic by supporting group validation, providing cleaner code, better maintainability, and higher development efficiency for Java backend developers.

Java Architect Essentials
Java Architect Essentials
Java Architect Essentials
Using @Validated in Spring Boot to Eliminate Repetitive Validation Code

In Spring Boot projects, developers often face repetitive validation code when handling user input, typically using the @Valid annotation or writing manual checks for each field. This leads to boilerplate code and maintenance challenges.

The @Validated annotation offers a powerful alternative that enables group validation, allowing developers to define validation groups and apply them selectively in different scenarios, dramatically reducing code duplication.

Below is a simple example of a data model with standard validation annotations:

public class User {

    @NotEmpty(message = "用户名不能为空")
    private String username;

    @Email(message = "邮箱格式不正确")
    private String email;

    @Min(value = 18, message = "年龄不能小于18")
    private Integer age;

    // Getter and Setter
}

When a controller receives a request, developers usually write something like:

@RestController
public class UserController {

    @PostMapping("/register")
    public ResponseEntity
registerUser(@RequestBody @Valid User user, BindingResult result) {
        if (result.hasErrors()) {
            return ResponseEntity.badRequest().body("输入数据不合法!");
        }
        return ResponseEntity.ok("注册成功!");
    }
}

While @Valid works for basic validation, it lacks flexibility for complex scenarios where different validation rules are required for the same object.

By switching to @Validated, developers can define validation groups:

public interface CreateGroup {}
public interface UpdateGroup {}

And apply them to the model fields:

public class User {

    @NotEmpty(groups = CreateGroup.class, message = "用户名不能为空")
    private String username;

    @Email(groups = {CreateGroup.class, UpdateGroup.class}, message = "邮箱格式不正确")
    private String email;

    @Min(value = 18, groups = CreateGroup.class, message = "年龄不能小于18")
    private Integer age;

    // Getter and Setter
}

In the controller, the appropriate group can be specified for each endpoint:

@RestController
public class UserController {

    @PostMapping("/register")
    public ResponseEntity
registerUser(@RequestBody @Validated(CreateGroup.class) User user, BindingResult result) {
        if (result.hasErrors()) {
            return ResponseEntity.badRequest().body("输入数据不合法!");
        }
        return ResponseEntity.ok("注册成功!");
    }

    @PutMapping("/update")
    public ResponseEntity
updateUser(@RequestBody @Validated(UpdateGroup.class) User user, BindingResult result) {
        if (result.hasErrors()) {
            return ResponseEntity.badRequest().body("更新数据不合法!");
        }
        return ResponseEntity.ok("更新成功!");
    }
}

The design philosophy behind @Validated is to provide a flexible validation mechanism that avoids massive duplicated code in complex business scenarios. By defining custom groups, developers can tailor validation rules to specific operations, improving code clarity and maintainability.

Practical usage examples include an e‑commerce platform where registration only validates basic user information, while updates require additional checks. Using @Validated with groups streamlines such logic and keeps the codebase clean.

Key advantages of @Validated are:

Reduced code redundancy : Validation logic is centralized and applied via annotations.

Flexible validation mechanism : Different groups can be selected per use case.

Enhanced maintainability : Validation rules are clearly grouped, improving readability.

Increased development efficiency : Less boilerplate means faster implementation of new features.

In summary, proper use of @Validated in Spring Boot not only simplifies validation code but also promotes consistency across a development team, leading to higher code quality and faster delivery.

backendJavaValidationSpringBootAnnotationGroup Validation@Validated
Java Architect Essentials
Written by

Java Architect Essentials

Committed to sharing quality articles and tutorials to help Java programmers progress from junior to mid-level to senior architect. We curate high-quality learning resources, interview questions, videos, and projects from across the internet to help you systematically improve your Java architecture skills. Follow and reply '1024' to get Java programming resources. Learn together, grow together.

0 followers
Reader feedback

How this landed with the community

login Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.