Backend Development 11 min read

Parameter Validation in Spring Boot: @Valid, @Validated, and Custom Annotations

Spring Boot offers several ways to validate request parameters—including the @Valid and @Validated annotations and custom validation annotations—each with its own strengths, allowing developers to enforce data integrity, improve code quality, and enhance user experience across different scenarios.

Java Captain
Java Captain
Java Captain
Parameter Validation in Spring Boot: @Valid, @Validated, and Custom Annotations

In a Spring Boot application, parameter validation is crucial for ensuring logical correctness and preventing invalid data input. Effective validation improves code quality and user experience. This article introduces several approaches to implement parameter validation in Spring Boot and discusses their advantages and disadvantages to help developers choose the most suitable method.

1. Using Spring MVC's @Valid Annotation

Spring MVC provides the @Valid annotation for parameter validation at the controller layer. By adding @Valid to request parameters or request bodies together with JSR‑303/JSR‑380 constraints such as @NotNull and @Size, developers can easily perform validation.

Example code:

@RestController
public
class
UserController
{
@PostMapping
(
"/users"
)
public
ResponseEntity<?> createUser(
@Valid
@RequestBody
UserDTO userDTO) {
// 业务逻辑处理
return
ResponseEntity.ok().build();
}
}
public
class
UserDTO
{
@NotNull
private
Long id;
@Size
(min =
1
, max =
50
)
private
String name;
// getters and setters
}

When a client sends a POST request to /users , Spring MVC automatically validates the UserDTO object. If validation fails, a MethodArgumentNotValidException is thrown, which can be handled with custom exception logic.

2. Using Spring Boot's @Validated Annotation

The @Validated annotation, provided by Spring Boot, works similarly to @Valid but offers more power and flexibility, supporting validation groups, nested validation, and other advanced features.

Example code:

@RestController
@Validated
public
class
UserController
{
@PostMapping
(
"/users"
)
public
ResponseEntity<?> createUser(
@RequestBody
@Validated
UserDTO userDTO) {
// 业务逻辑处理
return
ResponseEntity.ok().build();
}
}
public
class
UserDTO
{
@NotNull
(groups = Create
.
class
)
private
Long
id
;
@Size
(min =
1
, max =
50
, groups = {Create
.
class
,
Update
.
class
})
private
String
name
;
// getters and setters
public
interface
Create
{}
public
interface
Update
{}
}

By defining interfaces as validation groups, different validation rules can be applied in different scenarios—for example, validating only the id field when creating a user and both id and name when updating.

3. Custom Validation Annotations

Beyond the standard JSR‑303/JSR‑380 constraints, Spring Boot also supports custom validation annotations. Developers can define their own validation rules and implement them via custom annotations.

Example code:

@Target
({ElementType.FIELD, ElementType.PARAMETER})
@Retention
(RetentionPolicy.RUNTIME)
@Constraint
(validatedBy = UniqueUserNameValidator
.
class
)
public
@
interface
UniqueUserName
{
String
message
()
default
"用户名必须唯一"
;
Class<?>[] groups()
default
{};
Class<? extends Payload>[] payload()
default
{};
}
public
class
UniqueUserNameValidator
implements
ConstraintValidator
<
UniqueUserName
,
String
>
{
@Autowired
private
UserService userService;
@Override
public
void
initialize
(UniqueUserName constraintAnnotation)
{
}
@Override
public
boolean
isValid
(String value, ConstraintValidatorContext context)
{
return
userService.checkUserNameUnique(value);
}
}
public
class
UserDTO
{
@UniqueUserName
private
String userName;
// getters and setters
}

The example defines a @UniqueUserName annotation to ensure usernames are unique. By implementing ConstraintValidator , custom validation logic is provided, and the annotation can be applied to fields in DTO classes for automatic validation by Spring Boot.

Conclusion

Spring Boot provides multiple parameter‑validation solutions. Developers can use @Valid or @Validated for straightforward validation, employ validation groups for flexible scenario‑based rules, or create custom annotations for project‑specific requirements. Whichever approach is chosen, emphasis should be placed on code quality, user experience, and accurate validation.

JavaSpring BootCustom AnnotationParameter Validation@Validated@Valid
Java Captain
Written by

Java Captain

Focused on Java technologies: SSM, the Spring ecosystem, microservices, MySQL, MyCat, clustering, distributed systems, middleware, Linux, networking, multithreading; occasionally covers DevOps tools like Jenkins, Nexus, Docker, ELK; shares practical tech insights and is dedicated to full‑stack Java development.

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.