@Valid and @Validated have almost the same name, so it’s easy to get stuck on which one to use. Swap one for the other and your groups may stop working, nested DTOs may skip validation, or a different exception type may be thrown.
Here’s the short answer. Use @Valid most of the time. Use @Validated when you need to specify groups, or when you want to enable method validation in the Service layer or other non-Controller classes. In both cases, validation of nested objects comes from @Valid on the field.
This article only covers how to decide which one to use. For details on each annotation, see the article on implementing validation with @Valid and the article on group and method validation with @Validated.
Quick Reference Table
| Item | @Valid | @Validated |
|---|---|---|
| Package | jakarta.validation.Valid | org.springframework.validation.annotation.Validated |
| Specification | Jakarta Bean Validation standard | Spring-specific |
| Where it can be placed | Fields, methods, constructors, parameters, type arguments | Types (classes), methods, parameters |
| Specifying groups | Not supported (Default only) | Supported |
| Cascading to nested objects | Cascades when placed on a field | Does not mark cascading |
| Method validation | Does not enable it | Enables it when placed on a class |
“Does not mark cascading” doesn’t mean that putting @Validated on a parameter stops cascading. Whichever annotation the parameter has, @Valid on the field decides whether nested objects get validated.
Here’s what to use in each place:
- On
@RequestBody, use@Valid. If you need groups, use@Validated(YourGroup.class) - On nested DTO fields, use
@Valid - For List elements, put
@Validon the type argument (List<@Valid Item>) - On
@RequestParam/@PathVariable, put constraints such as@Mindirectly - In the Service layer, put
@Validatedon the class and either@Validor constraint annotations on the parameters
Prerequisites and Sample DTOs
This article assumes Spring Boot 3.5.x (Spring Framework 6.2.x), Hibernate Validator 8.0.x, and Java 21. The expected results in the tests below are based on the Validation and Method Validation sections of the Spring Framework reference documentation. Run them once on your own patch version to confirm.
The rules in the reference documentation are the same for Spring Boot 4.x (Framework 7, Hibernate Validator 9). On the test side, though, @WebMvcTest has moved to the org.springframework.boot.webmvc.test.autoconfigure package in the spring-boot-webmvc-test module, so update your imports.
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-validation</artifactId>
</dependency>
These DTOs are used in every scenario. They’re public types, so put each one in its own file.
// OnCreate.java / OnUpdate.java
public interface OnCreate {}
public interface OnUpdate {}
// Address.java / Item.java(import jakarta.validation.constraints.NotBlank)
public record Address(@NotBlank String city) {}
public record Item(@NotBlank String name) {}
// UserRequest.java
import jakarta.validation.Valid;
import jakarta.validation.constraints.NotBlank;
import jakarta.validation.constraints.NotNull;
import jakarta.validation.constraints.Null;
import java.util.List;
public record UserRequest(
@Null(groups = OnCreate.class)
@NotNull(groups = OnUpdate.class)
Long id,
@NotBlank String name,
@Valid Address address,
List<@Valid Item> items) {}
// NoCascadeRequest.java(場面3の失敗例用。address に @Valid がない)
public record NoCascadeRequest(@NotBlank String name, Address address) {}
The tests use @WebMvcTest and MockMvc. For the basics, see the article on writing Controller unit tests with MockMvc.
Scenario 1: Specifying Groups (@RequestBody)
Say you don’t want clients to send an id when creating a new resource. Let’s compare two endpoints side by side.
import jakarta.validation.Valid;
import org.springframework.http.ResponseEntity;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
@RestController
@RequestMapping("/users")
class UserController {
@PostMapping("/valid")
ResponseEntity<Void> withValid(@Valid @RequestBody UserRequest req) {
return ResponseEntity.ok().build();
}
@PostMapping("/validated")
ResponseEntity<Void> withValidated(
@Validated(OnCreate.class) @RequestBody UserRequest req) {
return ResponseEntity.ok().build();
}
@PostMapping("/no-cascade") // 場面3で使う
ResponseEntity<Void> noCascade(@Valid @RequestBody NoCascadeRequest req) {
return ResponseEntity.ok().build();
}
}
We send one JSON body that includes an id and another with an empty name.
import static org.assertj.core.api.Assertions.assertThat;
import static org.springframework.http.MediaType.APPLICATION_JSON;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
@WebMvcTest(UserController.class)
class GroupTest {
@Autowired MockMvc mockMvc;
String withId = """
{"id": 1, "name": "taro", "address": {"city": "Tokyo"}, "items": []}
""";
String blankName = """
{"name": "", "address": {"city": "Tokyo"}, "items": []}
""";
@Test
void validではgroupsの制約が無視される() throws Exception {
mockMvc.perform(post("/users/valid").contentType(APPLICATION_JSON).content(withId))
.andExpect(status().isOk());
}
@Test
void validatedならOnCreateの制約が効く() throws Exception {
mockMvc.perform(post("/users/validated").contentType(APPLICATION_JSON).content(withId))
.andExpect(status().isBadRequest())
.andExpect(r -> assertThat(r.getResolvedException())
.isInstanceOf(MethodArgumentNotValidException.class));
}
@Test
void OnCreateだけだとDefaultのNotBlankが効かない() throws Exception {
mockMvc.perform(post("/users/validated").contentType(APPLICATION_JSON).content(blankName))
.andExpect(status().isOk());
}
}
@Valid only validates the Default group, so the @Null with groups = OnCreate.class is ignored and the response is 200.
The third test is the trap. With @Validated(OnCreate.class), only OnCreate gets validated, so the @NotBlank on name, which has no groups, is skipped. Nested objects are validated with the same groups, so address.city isn’t validated either.
To include Default as well, write the parameter like this:
@PostMapping("/validated")
ResponseEntity<Void> withValidated(
@Validated({OnCreate.class, Default.class}) @RequestBody UserRequest req) {
return ResponseEntity.ok().build();
}
// import jakarta.validation.groups.Default;
Declaring public interface OnCreate extends Default {} has the same effect. In that case the third test returns 400, so change its expected result. If you also need to control the validation order, see the article on @GroupSequence.
Scenario 2: Validating Service-Layer Parameters
Outside Controllers, adding @Valid to a parameter does nothing on its own. When you put @Validated on the class, MethodValidationPostProcessor creates a proxy that runs the validation.
import jakarta.validation.Valid;
import jakarta.validation.groups.Default;
import java.util.List;
import org.springframework.stereotype.Service;
import org.springframework.validation.annotation.Validated;
@Service
@Validated // メソッドバリデーションを有効にするスイッチ
public class UserService {
public void register(@Valid UserRequest req) { }
// グループはメソッドに指定。Default を含めないと name の @NotBlank が外れる
@Validated({OnUpdate.class, Default.class})
public void update(@Valid UserRequest req) { }
public void registerAll(List<UserRequest> reqs) {
reqs.forEach(this::register); // 自己呼び出しなので検証されない
}
}
The two annotations do different jobs. @Validated on the class turns validation on, and @Valid on the parameter validates the DTO’s contents.
The call to this.register() from registerAll doesn’t go through the proxy, so it isn’t validated. This is the same reason @Transactional and @Cacheable don’t work on self-invocation. It’s covered in detail in the article on why annotations don’t work on self-invocation.
For the test, we add a Controller that passes the request to the Service without @Valid. If validation runs here, it must be coming from the Service layer.
@RestController
class ServiceCallController {
private final UserService userService;
ServiceCallController(UserService userService) { this.userService = userService; }
@PostMapping("/service/users")
void register(@RequestBody UserRequest req) { // @Valid なし
userService.register(req);
}
}
@WebMvcTest includes ValidationAutoConfiguration, so the UserService brought in with @Import also gets a proxy. The tests from here on use the same imports as Scenario 1, plus the two below.
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import jakarta.validation.ConstraintViolationException;
import org.springframework.context.annotation.Import;
@WebMvcTest(ServiceCallController.class)
@Import(UserService.class)
class ServiceValidationTest {
@Autowired MockMvc mockMvc;
@Test
void service層の違反はConstraintViolationException() {
String body = """
{"name": "", "address": {"city": "Tokyo"}, "items": []}
""";
assertThatThrownBy(() -> mockMvc.perform(
post("/service/users").contentType(APPLICATION_JSON).content(body)))
.hasCauseInstanceOf(ConstraintViolationException.class);
}
}
Spring MVC’s standard exception resolvers don’t handle this exception. When an exception isn’t handled, FrameworkServlet wraps it in a ServletException and rethrows it, so in MockMvc you check the cause with hasCauseInstanceOf. On a real server, the request is forwarded to /error and returns 500. To see how to test a handler that turns this into 400, see the article on testing @RestControllerAdvice exception handlers.
If you set adaptConstraintViolations on MethodValidationPostProcessor to true, the exception becomes Spring’s MethodValidationException instead. The default is false.
Scenario 3: Validating Nested DTOs and List Elements
Only @Valid on a field or a type argument marks an object for cascaded validation. First, let’s look at what goes wrong with NoCascadeRequest, which has no @Valid. These tests are added to GroupTest from Scenario 1.
@Test
void フィールドにValidがないとネストは素通り() throws Exception {
String body = """
{"name": "taro", "address": {"city": ""}}
""";
mockMvc.perform(post("/users/no-cascade").contentType(APPLICATION_JSON).content(body))
.andExpect(status().isOk());
}
@Test
void ネストとList要素のエラー() throws Exception {
String body = """
{"name": "taro", "address": {"city": ""},
"items": [{"name": "a"}, {"name": ""}]}
""";
mockMvc.perform(post("/users/valid").contentType(APPLICATION_JSON).content(body))
.andExpect(status().isBadRequest())
.andExpect(r -> {
var ex = (MethodArgumentNotValidException) r.getResolvedException();
assertThat(ex.getBindingResult().getFieldErrors())
.extracting(FieldError::getField)
.containsExactlyInAnyOrder("address.city", "items[1].name");
});
}
Without @Valid, the request passes with 200 even though city is empty. With UserRequest, which has the annotation, errors come back with indexed field names such as items[1].name.
@Valid List<Item> also works for List elements, but putting it on the type argument shows more clearly that the elements are what get validated.
@Validated can’t be placed on fields (it’s a compile error), so it can’t replace @Valid for nested validation. To accept a list directly as the request body, see the article on validating List DTOs and @RequestParam.
Scenario 4: Adding @Min to @RequestParam or @PathVariable
The answer here depends on your version. Starting with Spring Boot 3.2 (Spring Framework 6.1), Controllers have built-in method validation.
import jakarta.validation.constraints.Min;
import java.util.List;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
@RestController
class PageController {
@GetMapping("/items")
List<String> list(@RequestParam @Min(1) int page) { return List.of(); }
}
@Validated // 3.1以前の書き方
@RestController
class LegacyPageController {
@GetMapping("/legacy/items")
List<String> list(@RequestParam @Min(1) int page) { return List.of(); }
}
Let’s compare the two with page=0. Use the imports from Scenario 2, and add a static import for MockMvcRequestBuilders.get and an import for org.springframework.web.method.annotation.HandlerMethodValidationException.
@WebMvcTest({PageController.class, LegacyPageController.class})
class RequestParamTest {
@Autowired MockMvc mockMvc;
@Test
void validatedなしは400() throws Exception {
mockMvc.perform(get("/items").param("page", "0"))
.andExpect(status().isBadRequest())
.andExpect(r -> assertThat(r.getResolvedException())
.isInstanceOf(HandlerMethodValidationException.class));
}
@Test
void クラスにvalidatedがあるとConstraintViolationException() {
assertThatThrownBy(() -> mockMvc.perform(get("/legacy/items").param("page", "0")))
.hasCauseInstanceOf(ConstraintViolationException.class);
}
}
As the reference documentation explains, when the class has @Validated, validation runs in the AOP proxy instead. The result is a ConstraintViolationException, which becomes a 500 if no handler catches it.
On 3.2 or later, remove @Validated from your Controller classes. On 3.1 and earlier, constraints were ignored without it, which is why older articles say it’s “required.”
One more thing: from 6.1, if any method parameter (including the @RequestBody parameter itself) or the return value has a constraint such as @Min placed directly on it, method validation applies to the whole method. When that happens, @Valid @RequestBody violations are also reported as HandlerMethodValidationException.
Exceptions and HTTP Status by Scenario
| Scenario | Exception thrown | Default |
|---|---|---|
@RequestBody with @Valid / @Validated | MethodArgumentNotValidException (from 6.1, HandlerMethodValidationException if a parameter or the return value has a constraint placed directly on it) | 400 |
Constraints on @RequestParam etc. (3.2+, no @Validated on the class) | HandlerMethodValidationException | 400 |
Controller with @Validated on the class, Service layer | ConstraintViolationException | 500 (if no handler) |
To map ConstraintViolationException to 400 or use a consistent response format, see the article on returning consistent error responses from a REST API.
Troubleshooting by Symptom
- Group constraints don’t apply → You’re still using
@Valid @NotBlankstopped working after switching to@Validated(OnCreate.class)→ Default is no longer included- Nested DTOs aren’t validated → The field is missing
@Valid - Validation doesn’t run in the Service layer → The class is missing
@Validated, or the method is called from inside the same class @RequestParamviolations return 500 →@Validatedis still on the Controller
For the available constraint annotations and how they handle null, see the list of validation annotations.
Summary
On Spring Boot 3.2 or later, the cleanest approach is to leave @Validated off your Controller classes and use it only in the Service layer. That way the Controller side only throws two exception types, and both return 400.
To go deeper into group design, see the @Validated article. To decide how to handle ConstraintViolationException instead of returning 500, see the exception handling article.