0Pricing
Spring Boot 4 Microservices & REST APIs · 강의

사용자 지정 검증기

나만의 검증 제약 조건을 작성해 보세요.

사용자 지정 검증기은(는) CoddyKit의 무료 Spring Boot 4 Microservices & REST APIs 강의입니다. 이것은 4개 중 2번째 강의입니다. 아래에서 전체 강의를 무료로 읽을 수 있으며, 내장 코드 에디터와 24/7 AI 튜터와 함께 브라우저에서 직접 실습할 수 있습니다. 이 강의는 Spring Boot 4 Microservices & REST APIs 학습 경로의 일부이며, 진행 상황이 웹과 CoddyKit 앱에 동기화됩니다. Spring Boot 4 Microservices & REST APIs 강의에는 총 4개의 강의가 포함되어 있습니다.

이 강의의 일부는 아직 번역되지 않았으며 영어로 표시됩니다.

When Built-ins Are Not Enough

Standard constraints cannot express every rule — a valid coupon code format, a phone number for a region, or a value that must exist in the database. For these you write a custom constraint backed by a validator.

Two Parts of a Custom Constraint

A custom constraint has two pieces:

  • An annotation that you place on fields or parameters
  • A ConstraintValidator that contains the actual checking logic

Defining the Annotation

Create the annotation and link it to its validator with @Constraint. Declare the standard message, groups, and payload members required by the spec.

@Target({ FIELD, PARAMETER })
@Retention(RUNTIME)
@Constraint(validatedBy = StrongPasswordValidator.class)
public @interface StrongPassword {
    String message() default "Password is not strong enough";
    Class<?>[] groups() default {};
    Class<? extends Payload>[] payload() default {};
}

Implementing ConstraintValidator

The validator implements ConstraintValidator<Annotation, Type> and overrides isValid. Return true when the value satisfies the rule.

public class StrongPasswordValidator
        implements ConstraintValidator<StrongPassword, String> {
    @Override
    public boolean isValid(String value, ConstraintValidatorContext ctx) {
        if (value == null) return true; // let @NotNull handle null
        return value.length() >= 8
            && value.chars().anyMatch(Character::isDigit)
            && value.chars().anyMatch(Character::isUpperCase);
    }
}

Null-Handling Convention

By convention a custom validator treats null as valid, delegating null-checking to @NotNull. This keeps constraints composable — each rule does one job.

Using the Custom Constraint

Apply your annotation just like a built-in one. Combined with @Valid on the controller, it participates in the normal validation flow.

public class CreateUserRequest {
    @NotBlank
    @StrongPassword
    private String password;
}

Custom Violation Messages

Inside isValid you can disable the default message and add a contextual one, useful when a single annotation enforces several sub-rules.

ctx.disableDefaultConstraintViolation();
ctx.buildConstraintViolationWithTemplate(
        "Password must include a digit and an uppercase letter")
   .addConstraintViolation();
return false;

Injecting Beans into a Validator

A ConstraintValidator is a Spring bean, so it can use constructor injection — enabling rules that consult a repository or service, such as uniqueness checks.

public class UniqueEmailValidator
        implements ConstraintValidator<UniqueEmail, String> {
    private final UserRepository repo;
    public UniqueEmailValidator(UserRepository repo) { this.repo = repo; }
    @Override
    public boolean isValid(String email, ConstraintValidatorContext ctx) {
        return email == null || !repo.existsByEmail(email);
    }
}

Class-Level Constraints

Some rules span multiple fields — "password must equal confirmPassword." Target the annotation at TYPE and validate the whole object, accessing several fields together.

@Target(TYPE)
@Retention(RUNTIME)
@Constraint(validatedBy = PasswordsMatchValidator.class)
public @interface PasswordsMatch {
    String message() default "Passwords do not match";
    Class<?>[] groups() default {};
    Class<? extends Payload>[] payload() default {};
}

Initialization Hook

Override initialize to capture attributes from the annotation instance, such as a configurable minimum length, before validation runs.

@Override
public void initialize(StrongPassword ann) {
    this.minLength = ann.minLength();
}

Keep Validators Pure and Fast

Validators run on every request, so keep them quick and side-effect-free where possible. Database-backed checks are fine but should be indexed and lightweight to avoid slowing request handling.

Quick Check

Test your understanding of custom validators.

Recap

Custom validators extend Bean Validation.

  • A constraint is an @Constraint annotation plus a ConstraintValidator
  • Override isValid; treat null as valid by convention
  • Validators are beans, so they support constructor injection
  • Use class-level constraints for cross-field rules
  • Customize messages via the validation context

자주 묻는 질문

“사용자 지정 검증기” 강의는 무료인가요?

네 — “사용자 지정 검증기” 전체 내용을 이 웹사이트에서 무료로 읽을 수 있습니다. 인터랙티브하게 실습하려면(내장 코드 에디터와 24/7 AI 튜터), CoddyKit PRO로 업그레이드하면 Spring Boot 4 Microservices & REST APIs 강의 전체를 잠금 해제할 수 있습니다. Spring Boot 4 Microservices & REST APIs 강의에는 총 4개의 강의가 포함되어 있습니다.

“사용자 지정 검증기”에서 뭘 배우나요?

나만의 검증 제약 조건을 작성해 보세요. 브라우저에서 직접 실행하는 실습 코드로 Spring Boot 4 Microservices & REST APIs을(를) 배우며, 24/7 AI 튜터가 강의를 진행하면서 질문에 답변해줍니다.

Spring Boot 4 Microservices & REST APIs을(를) 시작하는 데 경험이 필요한가요?

사전 경험은 필요하지 않습니다. CoddyKit의 Spring Boot 4 Microservices & REST APIs은(는) 초급자부터 고급 학습자까지를 위해 구성되어 있으므로, 여기서 시작하거나 처음부터 시작할 수 있으며 자신의 속도대로 진행할 수 있습니다. 이것은 4개 중 2번째 강의입니다.

“사용자 지정 검증기” 강의는 얼마나 걸리나요?

대부분의 CoddyKit 강의는 약 5~10분이 소요됩니다. 각 강의는 간결하고 인터랙티브하여 꾸준한 진행이 가능하며, 웹과 앱에서 중단한 부분부터 바로 시작할 수 있습니다.

이 Spring Boot 4 Microservices & REST APIs 강의에서 코드를 작성하고 실행할 수 있나요?

네. 모든 Spring Boot 4 Microservices & REST APIs 강의에는 내장 코드 에디터가 포함되어 있으므로, 브라우저에서 바로 실제 코드를 작성하고 실행한 후 즉시 AI 피드백을 받을 수 있습니다 — 로컬 설정이 필요 없습니다.

이 강의의 모든 강의

  1. @Valid로 빈 검증하기
  2. 사용자 지정 검증기
  3. @ControllerAdvice와 @ExceptionHandler
  4. 문제 세부 정보(RFC 7807)
← Spring Boot 4 Microservices & REST APIs(으)로 돌아가기