0Pricing
Spring Boot 4 Complete Guide · 课时

构建自定义约束注解

使用 ConstraintValidator 创建可复用的自定义验证器,实现特定于领域的验证逻辑。

构建自定义约束注解 是 CoddyKit 上的免费 Spring Boot 4 Complete Guide 课时。 这是第 2 节课,共 4 节。 你可以在下方免费阅读本课时的完整内容 — 然后在浏览器中使用内置代码编辑器和全天候 AI 导师进行实践。 这是 Spring Boot 4 Complete Guide 学习路径的一部分,你的进度在网页和 CoddyKit 应用中同步。 Spring Boot 4 Complete Guide 课程共包含 4 节课。

本课时的部分内容尚未翻译,以英文显示。

Why Custom Constraints?

Bean Validation ships with annotations like @NotNull, @Size, and @Email. But real applications have domain-specific rules that no built-in annotation covers.

  • A username must be lowercase and 3-20 chars
  • A phone number must match your country's format
  • A status field must be one of an allowed enum set

Instead of writing manual checks in every controller or service, you can build a reusable custom constraint annotation that plugs into the same validation pipeline as the built-in ones.

The Two Pieces of a Custom Constraint

Every custom constraint in Spring Boot 4 (which uses Jakarta Bean Validation) has exactly two parts:

  • The annotation — what you write on a field, e.g. @ValidUsername. It declares metadata and points to a validator.
  • The ConstraintValidator — a class containing the actual isValid() logic.

The @Constraint meta-annotation links the two together. When validation runs, the framework instantiates your validator and calls isValid() for each annotated field.

Defining the Annotation

A custom constraint annotation must declare three standard attributes: message, groups, and payload. The @Constraint(validatedBy = ...) wires it to a validator class.

Note the imports come from jakarta.validation, not the old javax.validation.

import jakarta.validation.Constraint;
import jakarta.validation.Payload;
import java.lang.annotation.*;

@Documented
@Constraint(validatedBy = UsernameValidator.class)
@Target({ ElementType.FIELD, ElementType.PARAMETER })
@Retention(RetentionPolicy.RUNTIME)
public @interface ValidUsername {
    String message() default "invalid username";
    Class<?>[] groups() default {};
    Class<? extends Payload>[] payload() default {};
}

Understanding @Target and @Retention

Two meta-annotations control where and when your constraint applies:

  • @Target — where the annotation can be placed. FIELD for entity fields, PARAMETER for method args, METHOD for getters, TYPE_USE for generics like List<@ValidUsername String>.
  • @Retention(RUNTIME) — the annotation must survive into runtime so the validation engine can read it via reflection. This is mandatory; SOURCE or CLASS retention would make the constraint invisible.

Writing the ConstraintValidator

The validator implements ConstraintValidator<A, T>, where A is your annotation type and T is the type of the value being validated (e.g. String).

The isValid() method returns true if valid. A key rule: treat null as valid and let @NotNull handle nullness separately. This keeps each constraint focused on one concern.

import jakarta.validation.ConstraintValidator;
import jakarta.validation.ConstraintValidatorContext;

public class UsernameValidator
        implements ConstraintValidator<ValidUsername, String> {

    @Override
    public boolean isValid(String value, ConstraintValidatorContext ctx) {
        if (value == null) {
            return true; // let @NotNull handle null
        }
        return value.matches("^[a-z0-9_]{3,20}$");
    }
}

Applying the Constraint

Once defined, your constraint is used exactly like a built-in one. Place it on a DTO field and combine it with other constraints. Spring evaluates all of them when the object is validated.

Use @NotNull alongside @ValidUsername since the validator deliberately allows null.

import jakarta.validation.constraints.NotNull;

public record RegisterRequest(
        @NotNull
        @ValidUsername(message = "username must be 3-20 lowercase chars")
        String username,

        @NotNull
        String password
) {}

Triggering Validation in a Controller

To run validation on incoming request bodies, annotate the parameter with @Valid. If any constraint fails, Spring throws a MethodArgumentNotValidException before your method body runs.

The message you set on the annotation becomes the error message reported back to the client.

import jakarta.validation.Valid;
import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping("/api/users")
public class UserController {

    @PostMapping("/register")
    public String register(@Valid @RequestBody RegisterRequest req) {
        return "registered: " + req.username();
    }
}

Customizing the Error Message Dynamically

Sometimes a static message isn't enough — you want the message to reflect why validation failed. Use the ConstraintValidatorContext to disable the default message and build a custom one.

You must call disableDefaultConstraintViolation() first, then add your own violation, otherwise both messages appear.

@Override
public boolean isValid(String value, ConstraintValidatorContext ctx) {
    if (value == null) return true;
    if (value.length() < 3 || value.length() > 20) {
        ctx.disableDefaultConstraintViolation();
        ctx.buildConstraintViolationWithTemplate(
                "username length must be between 3 and 20")
           .addConstraintViolation();
        return false;
    }
    return value.matches("^[a-z0-9_]+$");
}

Passing Parameters to Your Constraint

Make constraints configurable by adding attributes to the annotation. For example, a @ValidUsername that accepts min and max length.

The validator reads these in initialize(), which runs once before isValid() calls.

public @interface ValidUsername {
    String message() default "invalid username";
    int min() default 3;
    int max() default 20;
    Class<?>[] groups() default {};
    Class<? extends Payload>[] payload() default {};
}

Reading Parameters in initialize()

Override initialize() to capture the annotation's attribute values into fields. The framework calls it once per validator instance, before any isValid() invocation.

This lets one validator class serve many different configurations.

public class UsernameValidator
        implements ConstraintValidator<ValidUsername, String> {

    private int min;
    private int max;

    @Override
    public void initialize(ValidUsername ann) {
        this.min = ann.min();
        this.max = ann.max();
    }

    @Override
    public boolean isValid(String value, ConstraintValidatorContext ctx) {
        if (value == null) return true;
        return value.length() >= min && value.length() <= max
                && value.matches("^[a-z0-9_]+$");
    }
}

Pure-Java: The Validation Logic Standalone

The core regex and length logic is plain Java you can test without any framework. Here is the same rule expressed as a runnable program to prove the logic before wiring it into Spring.

This isolation makes your validators easy to unit test.

public class Main {
    static boolean isValidUsername(String value, int min, int max) {
        if (value == null) return true;
        return value.length() >= min && value.length() <= max
                && value.matches("^[a-z0-9_]+$");
    }

    public static void main(String[] args) {
        System.out.println(isValidUsername("alice_99", 3, 20)); // true
        System.out.println(isValidUsername("Al", 3, 20));       // false
        System.out.println(isValidUsername("Bad Name", 3, 20)); // false
        System.out.println(isValidUsername(null, 3, 20));       // true
    }
}

Quick Check

You implement a custom ConstraintValidator for a String field. The field is optional, and a separate @NotNull already guards nullness. What should isValid() return when the value is null?

Recap

You learned how to build reusable custom constraint annotations in Spring Boot 4:

  • A constraint has two parts: the annotation (with message, groups, payload) and a ConstraintValidator.
  • @Constraint(validatedBy = ...) links them; @Retention(RUNTIME) and @Target control visibility and placement.
  • isValid() holds the logic and should treat null as valid, deferring to @NotNull.
  • Use initialize() to read annotation parameters, and ConstraintValidatorContext to craft dynamic messages.
  • Apply the constraint on DTO fields and trigger it with @Valid in controllers.

With these patterns, domain rules live in one tested place and plug seamlessly into Spring's validation pipeline.

常见问题解答

「构建自定义约束注解」课时是免费的吗?

是的 — 「构建自定义约束注解」的完整文本可在网页上免费阅读。要进行交互式练习(内置代码编辑器和全天候 AI 导师)并解锁 Spring Boot 4 Complete Guide 课程的其余内容,请升级到 CoddyKit PRO。 Spring Boot 4 Complete Guide 课程共包含 4 节课。

「构建自定义约束注解」这节课中我会学到什么?

使用 ConstraintValidator 创建可复用的自定义验证器,实现特定于领域的验证逻辑。 你通过在浏览器中直接运行的动手代码来练习 Spring Boot 4 Complete Guide,全天候 AI 导师会在你学习这节课的过程中回答你的问题。

学习 Spring Boot 4 Complete Guide 需要有经验吗?

无需任何先前经验。CoddyKit 上的 Spring Boot 4 Complete Guide 课程适合初学者到高级学习者,你可以从这里开始或从头开始,按照自己的节奏学习。 这是第 2 节课,共 4 节。

「构建自定义约束注解」课时需要多长时间?

大多数 CoddyKit 课程大约需要 5–10 分钟。每节课都很精短且互动,所以你能稳步进步,并在网页和应用中从离开的地方继续。

我能在这节 Spring Boot 4 Complete Guide 课中编写并运行代码吗?

能。每节 Spring Boot 4 Complete Guide 课都包含内置代码编辑器,你可以在浏览器中直接编写并运行真实代码,并获得即时 AI 反馈 — 无需本地设置。

此课程中的所有课时

  1. Bean Validation 约束与约束分组
  2. 构建自定义约束注解
  3. 使用 @ControllerAdvice 进行全局异常处理
  4. RFC 7807 Problem Detail 响应
← 返回 Spring Boot 4 Complete Guide