springspring-bootbean-validation

Does @Valid work without @Validated on @RestController?


In following blog entry.

https://www.baeldung.com/spring-boot-bean-validation

The author mentioned about how Spring Boot works with @Valid annotation.

@RestController
public class UserController {

    @PostMapping("/users")
    ResponseEntity<String> addUser(@Valid @RequestBody User user) {
        // persisting the user
        return ResponseEntity.ok("User is valid");
    }
    
    // standard constructors / other methods
    
}

When Spring Boot finds an argument annotated with @Valid, it automatically bootstraps the default JSR 380 implementation — Hibernate Validator — and validates the argument.

Is it true that @Valid works as expected on @RestController without @Validated?

Then what kind of stereo types required to be explicitly annotated with @Validated?


Solution

  • Yes @Valid will work without @Validated in @RestController.

    In Spring, we use JSR-303's @Valid annotation for method level validation. Moreover, we also use it to mark a member attribute for validation. However, this annotation doesn't support group validation. Groups help to limit the constraints applied during validation. One particular use case is UI wizards. Here, in the first step, we may have a certain sub-group of fields. In the subsequent step, there may be another group belonging to the same bean. Hence we need to apply constraints on these limited fields in each step, but @Valid doesn't support this. In this case, for group-level, we have to use Spring's @Validated, which is a variant of this JSR-303's @Valid. This is used at the method-level. And for marking member attributes, we continue to use the @Valid annotation.

    You can read more about this in this link.