Bean Validation 제약 조건과 제약 조건 그룹
그룹화를 적용한 Jakarta Bean Validation 주석으로 컨텍스트별 규칙을 강제합니다.
Bean Validation 제약 조건과 제약 조건 그룹은(는) CoddyKit의 무료 Spring Boot 4 Complete Guide 강의입니다. 이것은 4개 중 1번째 강의입니다. 아래에서 전체 강의를 무료로 읽을 수 있으며, 내장 코드 에디터와 24/7 AI 튜터와 함께 브라우저에서 직접 실습할 수 있습니다. 이 강의는 Spring Boot 4 Complete Guide 학습 경로의 일부이며, 진행 상황이 웹과 CoddyKit 앱에 동기화됩니다. Spring Boot 4 Complete Guide 강의에는 총 4개의 강의가 포함되어 있습니다.
이 강의의 일부는 아직 번역되지 않았으며 영어로 표시됩니다.
Why Bean Validation?
In a Spring Boot 4 application you constantly receive untrusted data: request bodies, query params, form submissions. Jakarta Bean Validation (the jakarta.validation API) lets you declare rules as annotations directly on your model fields instead of writing manual if checks everywhere.
- Declarative — the rule lives next to the field it protects.
- Centralized — Spring triggers validation automatically at the controller boundary.
- Consistent — the same annotated class can be validated in the web layer, service layer, or persistence layer.
The reference implementation behind the API is Hibernate Validator, pulled in by the spring-boot-starter-validation dependency.
Adding the Starter
Validation is not bundled with the web starter anymore, so you must add it explicitly. Once present, Hibernate Validator is auto-configured and Spring wires a Validator bean for you.
Add the dependency to your pom.xml:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-validation</artifactId>
</dependency>Annotating a DTO
You attach constraints to the fields of a Data Transfer Object. Each annotation carries an optional message and validation parameters.
@NotBlank— the string must contain at least one non-whitespace character.@Email— must look like a valid email address.@Size(min, max)— length must fall within range.@Min/@Max— numeric bounds.
public class UserRegistrationRequest {
@NotBlank(message = "Username is required")
@Size(min = 3, max = 20)
private String username;
@NotBlank
@Email(message = "Provide a valid email")
private String email;
@Min(value = 18, message = "Must be at least 18")
private int age;
// getters and setters
}Triggering Validation with @Valid
Annotating the DTO alone does nothing. You must tell Spring to validate the argument by placing @Valid on the controller method parameter. If validation fails, Spring throws a MethodArgumentNotValidException before your method body ever runs, and returns a 400 Bad Request.
@RestController
@RequestMapping("/api/users")
public class UserController {
@PostMapping
public ResponseEntity<String> register(
@Valid @RequestBody UserRegistrationRequest request) {
// reaches here only if all constraints pass
return ResponseEntity.ok("Registered " + request.getUsername());
}
}The Problem: One DTO, Many Contexts
Imagine the same UserRegistrationRequest is reused for two operations:
- Create — the client must NOT send an
id(the server generates it). - Update — the client MUST send an existing
idto know what to modify.
A field that should be @Null on create but @NotNull on update cannot be expressed with plain annotations, because they always fire. This is exactly the problem constraint groups solve.
Defining Constraint Groups
A constraint group is just a marker interface — an empty interface used purely as a tag. You create one per validation context.
Every constraint annotation accepts a groups attribute. When you assign a constraint to a group, that constraint only runs when validation is requested for that group.
public interface OnCreate {}
public interface OnUpdate {}Assigning Constraints to Groups
Now tag each constraint with the group(s) it belongs to. A constraint with no groups attribute implicitly belongs to the built-in Default group and runs unless you switch groups.
Here the id field obeys opposite rules depending on context:
public class ProductRequest {
@Null(groups = OnCreate.class,
message = "id must be empty when creating")
@NotNull(groups = OnUpdate.class,
message = "id is required when updating")
private Long id;
@NotBlank(groups = {OnCreate.class, OnUpdate.class})
private String name;
@Positive(groups = {OnCreate.class, OnUpdate.class})
private BigDecimal price;
// getters and setters
}Selecting a Group with @Validated
Here is the crucial distinction: @Valid always validates the Default group only and cannot select a group. To activate a specific group you must use Spring's @Validated annotation, which accepts the target group class.
Each endpoint picks the group that matches its operation:
@RestController
@RequestMapping("/api/products")
public class ProductController {
@PostMapping
public ResponseEntity<Void> create(
@Validated(OnCreate.class) @RequestBody ProductRequest req) {
// @Null id, @NotBlank name, @Positive price enforced
return ResponseEntity.status(HttpStatus.CREATED).build();
}
@PutMapping
public ResponseEntity<Void> update(
@Validated(OnUpdate.class) @RequestBody ProductRequest req) {
// @NotNull id enforced instead
return ResponseEntity.ok().build();
}
}@Valid vs @Validated
This pair trips up many developers, so commit it to memory:
@Valid— comes fromjakarta.validation. Works on fields for nested/cascading validation, but cannot specify a group (usesDefault).@Validated— comes fromorg.springframework.validation.annotation. Accepts group classes, and also enables method-level validation on Spring beans. Cannot be placed on a field for cascading.
Rule of thumb: use @Validated(Group.class) at the controller parameter to pick a group; use @Valid on inner object fields to cascade into them.
Cascading and Group Sequences
Two advanced needs come up often:
- Cascading — to validate a nested object, mark its field with
@Valid. Without it, the nested object's constraints are skipped. - Ordering — a
@GroupSequenceruns groups in order and stops at the first group that fails, so you can enforce cheap checks before expensive ones.
@GroupSequence({First.class, Second.class})
public interface OrderedChecks {}
public class OrderRequest {
@NotEmpty(groups = First.class)
private List<@Valid LineItem> items; // @Valid cascades into each item
@AssertTrue(groups = Second.class,
message = "Total must match line items")
public boolean isTotalConsistent() {
return /* expensive cross-field check */ true;
}
}Reading the Errors
When a grouped validation fails, the resulting MethodArgumentNotValidException still carries the standard BindingResult. You can translate it into a clean JSON response with a @RestControllerAdvice handler, mapping each field to its message.
@RestControllerAdvice
public class ValidationExceptionHandler {
@ExceptionHandler(MethodArgumentNotValidException.class)
@ResponseStatus(HttpStatus.BAD_REQUEST)
public Map<String, String> handle(MethodArgumentNotValidException ex) {
Map<String, String> errors = new HashMap<>();
ex.getBindingResult().getFieldErrors().forEach(err ->
errors.put(err.getField(), err.getDefaultMessage()));
return errors;
}
}Quick Check
Test your understanding of how Spring selects a constraint group.
Recap
You learned how to enforce context-specific validation rules with Jakarta Bean Validation in Spring Boot 4:
- Add
spring-boot-starter-validation, then annotate DTO fields with constraints like@NotBlank,@Email,@Size,@Min. - Trigger validation at the controller boundary; a failure yields a 400 via
MethodArgumentNotValidException. - Constraint groups are marker interfaces assigned via each annotation's
groupsattribute, letting one DTO carry different rules per operation (e.g.@Nullon create vs@NotNullon update). - Use
@Validated(Group.class)to select a group —@Validonly runs theDefaultgroup and is for cascading into nested objects. @GroupSequenceorders groups and short-circuits on the first failure;@Validon a collection cascades into each element.
자주 묻는 질문
“Bean Validation 제약 조건과 제약 조건 그룹” 강의는 무료인가요?
네 — “Bean Validation 제약 조건과 제약 조건 그룹” 전체 내용을 이 웹사이트에서 무료로 읽을 수 있습니다. 인터랙티브하게 실습하려면(내장 코드 에디터와 24/7 AI 튜터), CoddyKit PRO로 업그레이드하면 Spring Boot 4 Complete Guide 강의 전체를 잠금 해제할 수 있습니다. Spring Boot 4 Complete Guide 강의에는 총 4개의 강의가 포함되어 있습니다.
“Bean Validation 제약 조건과 제약 조건 그룹”에서 뭘 배우나요?
그룹화를 적용한 Jakarta Bean Validation 주석으로 컨텍스트별 규칙을 강제합니다. 브라우저에서 직접 실행하는 실습 코드로 Spring Boot 4 Complete Guide을(를) 배우며, 24/7 AI 튜터가 강의를 진행하면서 질문에 답변해줍니다.
Spring Boot 4 Complete Guide을(를) 시작하는 데 경험이 필요한가요?
사전 경험은 필요하지 않습니다. CoddyKit의 Spring Boot 4 Complete Guide은(는) 초급자부터 고급 학습자까지를 위해 구성되어 있으므로, 여기서 시작하거나 처음부터 시작할 수 있으며 자신의 속도대로 진행할 수 있습니다. 이것은 4개 중 1번째 강의입니다.
“Bean Validation 제약 조건과 제약 조건 그룹” 강의는 얼마나 걸리나요?
대부분의 CoddyKit 강의는 약 5~10분이 소요됩니다. 각 강의는 간결하고 인터랙티브하여 꾸준한 진행이 가능하며, 웹과 앱에서 중단한 부분부터 바로 시작할 수 있습니다.
이 Spring Boot 4 Complete Guide 강의에서 코드를 작성하고 실행할 수 있나요?
네. 모든 Spring Boot 4 Complete Guide 강의에는 내장 코드 에디터가 포함되어 있으므로, 브라우저에서 바로 실제 코드를 작성하고 실행한 후 즉시 AI 피드백을 받을 수 있습니다 — 로컬 설정이 필요 없습니다.
이 강의의 모든 강의
- Bean Validation 제약 조건과 제약 조건 그룹
- 사용자 지정 제약 조건 주석 구축
- @ControllerAdvice를 활용한 전역 예외 처리
- RFC 7807 Problem Detail 응답