Skip to content
ADevGuide
Go back

Spring Boot @Valid vs @Validated: An Easy In-Depth Comparison

Updated:

Spring Boot @Valid vs @Validated: An Easy In-Depth Comparison

Today we will be talking about “Spring Boot @Valid vs @Validated”. When it comes to building web applications, it’s essential to handle input validation to ensure data integrity and security. In Spring Boot, two commonly used annotations for input validation are @Valid and @Validated. In this blog post, we’ll delve into the differences between these two annotations, their use cases, and when to choose one over the other.

Table of Contents

Open Table of Contents

Understanding the Basics

Before diving into the comparison, let’s establish a fundamental understanding of what @Valid and @Validated do in a Spring Boot application.

@Valid

@Valid is a standard Java annotation, and it’s part of the Java Bean Validation framework (JSR 380). It is used to validate the properties of an object, typically within the context of a Spring MVC controller. This annotation triggers validation of the annotated object and its properties by the Bean Validation framework. If any validation constraints are violated, it will result in a MethodArgumentNotValidException being thrown, which can be handled by a global exception handler.

Here’s an example of how @Valid is used in a Spring Boot controller:

@RestController
@RequestMapping("/api/users")
public class UserController {

    @PostMapping
    public ResponseEntity<User> createUser(@RequestBody @Valid User user) {
        // Business logic to create a user
        return ResponseEntity.ok(user);
    }
}

In this example, the @Valid annotation is applied to the User object passed as a request body. The User object’s properties will be validated based on the constraints defined in the User class.

@Validated

@Validated is a Spring-specific annotation used for method-level validation. It is typically applied to controller methods and service methods to validate method parameters. Unlike @Valid, @Validated provides more fine-grained control over the validation process. It allows you to specify validation groups, enabling you to validate different groups of constraints at different points in your application.

Here’s an example of how @Validated is used:

@Service
@Validated
public class UserService {

    @NotNull(groups = {CreateUser.class})
    public User createUser(@Valid User user) {
        // Business logic to create a user
        return user;
    }
}

In this example, the @Validated annotation is applied to the UserService class, and the @NotNull constraint specifies that the createUser method should only be validated when the CreateUser validation group is targeted.

Now that we have a basic understanding of @Valid and @Validated, let’s explore the differences between the two.

Simple Guide To Dockerize Java Application Maven With Dockerfile [2020]

Key Differences

1. Scope of Application

The primary difference between @Valid and @Validated lies in their scope of application:

The choice between the two depends on where and how you want to perform validation in your application.

2. Validation Groups

Validation groups are a significant feature provided by @Validated. They allow you to group and validate constraints selectively based on specific use cases. This can be extremely useful in scenarios where you want to apply different sets of constraints in various situations.

For example, you might want to validate a user’s information differently when they are registering (requiring username, email, and password) compared to when they are updating their profile (where only email changes might be allowed).

With @Validated, you can define different validation groups and apply them as needed. This level of control is not available with @Valid.

3. Exception Handling

Another difference is in how exceptions are handled:

The choice between these two mechanisms depends on your project’s requirements. If you need finer-grained control over exception handling, @Validated is the way to go.

Use Cases

Now that we’ve explored the differences between @Valid and @Validated, let’s consider some common use cases for each annotation.

When to Use @Valid

Here’s an example use case for @Valid:

@RestController
@RequestMapping("/api/orders")
public class OrderController {

    @PostMapping
    public ResponseEntity<Order> createOrder(@RequestBody @Valid OrderDTO orderDTO) {
        // Business logic to create an order
        return ResponseEntity.ok(order);
    }
}

In this scenario, @Valid is an excellent choice for validating the orderDTO object.

When to Use @Validated

Here’s an example use case for @Validated:

@Service
@Validated
public class OrderService {

    @NotNull(groups = {CreateOrder.class})
    public Order createOrder(@Valid OrderDTO orderDTO) {
        // Business logic to create an order
        return order;
    }

    @NotNull(groups = {UpdateOrder.class})
    public Order updateOrder(@Valid OrderDTO orderDTO) {
        // Business logic to update an order
        return order;
    }
}

In this scenario, @Validated is beneficial as it allows you to define different validation groups (CreateOrder and UpdateOrder) and apply them to the createOrder and updateOrder methods.

All About Java Regular Expressions Regex 2019

Spring Boot @Valid vs @Validated: Best Practices

To make the most of @Valid and @Validated, consider the following best practices:

1. Organize Your Validation Logic

Whether you choose @Valid or @Validated, it’s essential to keep your validation logic organized. Create separate validation classes or methods to encapsulate your constraints, and then apply them where needed. This keeps your codebase clean and makes it easier to manage and maintain your validation rules.

2. Use Validation Groups Wisely

If you opt for @Validated, use validation groups to their full potential. This allows you to apply different sets of constraints based on the specific scenario. However, avoid overcomplicating your code with an excessive number of validation groups. Keep it simple and maintainable.

3. Customize Exception Handling

If you require customized exception handling for validation errors, consider using @Validated. You can define custom exception handling for each validation group, providing a more tailored experience for handling different validation scenarios.

4. Document

Your Validation Constraints

Whichever annotation you choose, document your validation constraints clearly. Use comments or annotations to describe the purpose of each constraint, making it easier for developers to understand and maintain the validation rules.

5. Consider Cross-Field Validation

For more complex validation scenarios that involve cross-field validation (where the validity of one field depends on the value of another), you may need to use custom validation logic in addition to standard Bean Validation constraints. Both @Valid and @Validated can work with custom validators to achieve this.

Official Documentation

https://spring.io/guides/gs/validating-form-input/

Conclusion

In Spring Boot, both @Valid and @Validated are essential tools for input validation. The choice between them depends on your specific use case and requirements.

Ultimately, the choice between @Valid and @Validated should align with your project’s architecture and validation needs. By understanding the differences and best practices for each, you can make informed decisions and build robust, well-validated Spring Boot applications.


Share this post on:

Previous Post
Vertical and Horizontal Database Sharding: A Comprehensive Comparison With Easy Analogy
Next Post
An Easy Step-By-Step Guide to Changing Server Port in a Spring Boot Application [4 ways]