Bean 验证:@NotNull、@Size、@Pattern
使用 Bean 验证约束标注 DTO,并在控制器中通过 @Valid 触发验证
Bean 验证:@NotNull、@Size、@Pattern 是 CoddyKit 上的免费 Java Academy 课时。 这是第 1 节课,共 4 节。 你可以在下方免费阅读本课时的完整内容 — 然后在浏览器中使用内置代码编辑器和全天候 AI 导师进行实践。 这是 Java Academy 学习路径的一部分,你的进度在网页和 CoddyKit 应用中同步。 Java Academy 课程共包含 4 节课。
什么是 Bean 验证
Bean 验证(Jakarta Bean 验证 3.0)为 Java 对象提供声明式约束注解。Spring Boot 会自动配置验证器,并通过 @Valid 或 @Validated 触发验证。
@NotNull、@NotEmpty、@NotBlank
@NotNull:值不能为 null。@NotEmpty:不能为 null 且不能为空(适用于字符串和集合)。@NotBlank:不能为 null、不能为空,也不能只包含空白字符。对于字符串,请优先使用 @NotBlank。
public record CreateUserRequest(
@NotBlank(message = "Name is required")
String name,
@NotBlank @Email
String email,
@NotNull
UserRole role
) {}@Size 与 @Length
@Size(min, max) 用于限制字符串、集合、映射和数组的大小。@Length(Hibernate)仅适用于字符串。为了可移植性,请优先使用 @Size。
@Size(min = 3, max = 50, message = "Name must be 3-50 characters")
private String name;
@Size(min = 1, max = 10, message = "Cart must have 1-10 items")
private List<CartItem> items;@Min、@Max、@Positive、@Range
数值约束:@Min/@Max 用于设置精确的边界,@Positive/@PositiveOrZero 用于限制符号,@DecimalMin/@DecimalMax 适用于 BigDecimal。
@Min(1) @Max(100)
private int quantity;
@DecimalMin("0.01") @DecimalMax("99999.99")
private BigDecimal price;
@Positive
private long orderId;使用 @Pattern 进行正则验证
@Pattern(regexp) 会根据正则表达式验证字符串。它适用于电话号码、邮政编码和自定义格式。
@Pattern(regexp = "^\\+?[1-9]\\d{7,14}$", message = "Invalid phone number")
private String phone;
@Pattern(regexp = "^[A-Z]{2}\\d{5}$", message = "Invalid postal code (e.g. AB12345)")
private String postalCode;@Email 与 @URL
@Email 会验证电子邮件格式(基本 RFC 5321)。@URL(Hibernate)会验证 URL 格式。由于它们允许 null,请始终将其与 @NotBlank 结合使用。
@NotBlank @Email
private String email;
// Hibernate-specific:
@URL(protocol = "https")
private String profileUrl;@Past、@Future、@PastOrPresent
时间约束用于验证日期和时间值。它适用于 LocalDate、LocalDateTime、Instant 等类型。
@Past(message = "Birth date must be in the past")
private LocalDate birthDate;
@Future(message = "Expiry must be in the future")
private LocalDate expiryDate;使用 @Valid 触发验证
将 @Valid 添加到控制器方法参数上。Spring 会验证该对象;验证失败时抛出 MethodArgumentNotValidException,并返回 400 错误请求。
@PostMapping("/users")
public ResponseEntity<UserDto> create(@Valid @RequestBody CreateUserRequest req) {
User user = userService.create(req);
return ResponseEntity.status(201).body(UserDto.from(user));
}在字段上使用 @Valid 进行级联验证
要验证嵌套对象,请在字段上添加 @Valid,同时保留类级别约束。
public record OrderRequest(
@NotNull @Valid
AddressRequest shippingAddress, // validates AddressRequest constraints too
@Valid @NotEmpty
List<@Valid LineItemRequest> items
) {}验证分组
使用分组在不同上下文中应用不同约束(例如创建与更新)。使用分组接口进行注解,并通过 @Validated(CreateGroup.class) 触发验证。
public interface CreateGroup {}
public interface UpdateGroup {}
public record UserRequest(
@NotBlank(groups = CreateGroup.class) String password,
@NotNull(groups = UpdateGroup.class) Long id
) {}
// Controller:
@PutMapping("/{id}")
public UserDto update(@Validated(UpdateGroup.class) @RequestBody UserRequest req) { ... }读取验证错误
在 @ControllerAdvice 中捕获 MethodArgumentNotValidException,提取字段错误并构建结构化错误响应。
@ExceptionHandler(MethodArgumentNotValidException.class)
public ResponseEntity<Map<String, String>> handleValidation(MethodArgumentNotValidException ex) {
Map<String, String> errors = new LinkedHashMap<>();
ex.getBindingResult().getFieldErrors().forEach(e ->
errors.put(e.getField(), e.getDefaultMessage()));
return ResponseEntity.badRequest().body(errors);
}快速检查
哪个注解可以验证 String 非 null 且非空白(而不仅仅是不包含空白字符)?
回顾
使用 Bean 验证约束为数据传输对象添加注解。在控制器中添加 @Valid 以触发验证。字符串使用 @NotBlank,长度使用 @Size,正则表达式使用 @Pattern,日期使用 @Past/@Future。在 @ControllerAdvice 中处理错误。
常见问题解答
「Bean 验证:@NotNull、@Size、@Pattern」课时是免费的吗?
是的 — 「Bean 验证:@NotNull、@Size、@Pattern」的完整文本可在网页上免费阅读。要进行交互式练习(内置代码编辑器和全天候 AI 导师)并解锁 Java Academy 课程的其余内容,请升级到 CoddyKit PRO。 Java Academy 课程共包含 4 节课。
「Bean 验证:@NotNull、@Size、@Pattern」这节课中我会学到什么?
使用 Bean 验证约束标注 DTO,并在控制器中通过 @Valid 触发验证 你通过在浏览器中直接运行的动手代码来练习 Java Academy,全天候 AI 导师会在你学习这节课的过程中回答你的问题。
学习 Java Academy 需要有经验吗?
无需任何先前经验。CoddyKit 上的 Java Academy 课程适合初学者到高级学习者,你可以从这里开始或从头开始,按照自己的节奏学习。 这是第 1 节课,共 4 节。
「Bean 验证:@NotNull、@Size、@Pattern」课时需要多长时间?
大多数 CoddyKit 课程大约需要 5–10 分钟。每节课都很精短且互动,所以你能稳步进步,并在网页和应用中从离开的地方继续。
我能在这节 Java Academy 课中编写并运行代码吗?
能。每节 Java Academy 课都包含内置代码编辑器,你可以在浏览器中直接编写并运行真实代码,并获得即时 AI 反馈 — 无需本地设置。
此课程中的所有课时
- Bean 验证:@NotNull、@Size、@Pattern
- 自定义约束注解
- 使用 @ControllerAdvice 进行全局异常处理
- RFC 7807 问题详情与一致的错误响应