0Pricing
Java Academy · Lesson

Custom Constraint Annotations

Create a custom @UniqueEmail annotation with a ConstraintValidator implementation.

When Standard Constraints Are Not Enough

Standard Bean Validation annotations cover common cases. For domain-specific rules (e.g., unique email, valid IBAN, password strength), create custom constraint annotations.

Defining the Constraint Annotation

Create an annotation with @Constraint(validatedBy = ...), required message, groups, and payload elements, and the appropriate retention/target.

import jakarta.validation.Constraint;
import jakarta.validation.Payload;
@Documented
@Constraint(validatedBy = UniqueEmailValidator.class)
@Target({ElementType.FIELD, ElementType.PARAMETER})
@Retention(RetentionPolicy.RUNTIME)
public @interface UniqueEmail {
    String message() default "Email already registered";
    Class<?>[] groups() default {};
    Class<? extends Payload>[] payload() default {};
}

All lessons in this course

  1. Bean Validation: @NotNull, @Size, @Pattern
  2. Custom Constraint Annotations
  3. Global Exception Handling with @ControllerAdvice
  4. RFC 7807 Problem Details and Consistent Error Responses
← Back to Java Academy