Spring
Validation
Valid
Validated
Java

Difference between Valid and Validated in Spring

Master System Design with Codemia

Enhance your system design skills with over 120 practice problems, detailed solutions, and hands-on exercises.

In the Spring Framework, @Valid and @Validated are both essential annotations used for validating input data, typically in the context of web applications using Spring MVC. Despite their apparent similarities, they have distinct purposes and functionalities. Understanding these differences can significantly enhance how validation is handled in your application. This article delves into the nuances of these two annotations, providing technical insights and practical examples.

The Basics of Bean Validation

Before we explore the differences between @Valid and @Validated, it's essential to grasp the underlying concept of Bean Validation.

Bean Validation is a Java specification (JSR 303 and its improved iteration, JSR 380) which provides a standardized way of validating data. Spring Framework supports this specification and integrates it using annotations. These annotations can be applied to Java Bean properties, method parameters, and return values.

Differences Between @Valid and @Validated

1. Origin

  • @Valid: This annotation is defined in the Java standard javax.validation package. It is a part of the Bean Validation API (JSR 303).
  • @Validated: This annotation is part of Spring and is located in the org.springframework.validation.annotation package. It is specific to Spring's infrastructure for validation.

2. Usage Context

  • @Valid: Primarily used for method parameter validation. It works straightforwardly with the JSR-303 Bean Validation framework.
  • @Validated: Apart from validating method parameters, it supports validation groups, which allows you to trigger validation rules conditionally based on the context.

3. Validation Group Support

  • @Valid: Does not support validation groups as it adheres strictly to the standard JSR-303 validation.
  • @Validated: Supports validation groups which is a feature provided by Spring to group different validations together. This is useful in scenarios where you want to apply different validation rules dynamically.

4. Validation Trigger

  • @Valid: Automatically triggers the validation process when used on method parameters.
  • @Validated: Requires Spring’s infrastructure to trigger validation and is often used in combination with other Spring features, such as method-level validation.

Practical Examples

Example 1: Using @Valid

java
1import javax.validation.constraints.NotNull;
2import javax.validation.Valid;
3
4public class UserController {
5
6    public ResponseEntity<String> createUser(@RequestBody @Valid User user) {
7        // Imagine User has some validation constraints
8        // The validation will be triggered when the user object is passed in the request body
9        return ResponseEntity.ok("User is valid");
10    }
11}
12
13public class User {
14    @NotNull
15    private String name;
16
17    // getters and setters
18}

In the above example, @Valid ensures that the User object provided in the request body complies with any validation constraints (e.g., @NotNull).

Example 2: Using @Validated

java
1import org.springframework.validation.annotation.Validated;
2import javax.validation.constraints.NotNull;
3import javax.validation.constraints.Min;
4
5@Validated
6public class OrderService {
7
8    public void placeOrder(@Min(1) int quantity, @NotNull String productName) {
9        // The validation is triggered here directly
10    }
11}

Here, @Validated is used on the class, and method parameters are validated based on their constraints when the method placeOrder is invoked.

Example 3: Validation Groups with @Validated

java
1public class User {
2    @NotNull(groups = BasicInfo.class)
3    private String name;
4
5    @Min(value = 18, groups = AdultCheck.class)
6    private Integer age;
7
8    public interface BasicInfo {}
9    public interface AdultCheck {}
10}
11
12@Validated
13public class RegistrationService {
14
15    public void registerUser(@Validated(User.BasicInfo.class) User user) {
16        // Only BasicInfo group validations are triggered
17    }
18}

In this example, validation groups are used to apply specific validation rules selectively.

Summary Table

Aspect@Valid@Validated
OriginJava (javax.validation)Spring (org.springframework.validation.annotation)
Validation Group SupportNoYes
Triggered InAny bean validation context Method parameters in controllersSpring-managed beans Method parameters in services Class-level validation
Primary UseBasic, standard validation usageAdvanced usages like group validation

Contextual Considerations

  • Error Handling: When using these annotations, it’s advisable to address and handle validation errors appropriately, often by leveraging exception handlers (@ExceptionHandler) or controller advice (@ControllerAdvice).
  • Integration with Other Frameworks: Both annotations seamlessly integrate with Spring MVC and other frameworks relying on the Java Bean Validation API, ensuring a consistent validation strategy across different layers of your application.

Conclusion

Understanding the differences between @Valid and @Validated allows developers to effectively and selectively apply validation logic in their applications. Utilizing the right annotation can lead to more robust input validation, ultimately enhancing application stability and user experience. As Spring continues to evolve, these tools remain foundational in building reliable Java applications.


Course illustration
Course illustration

All Rights Reserved.