在 Spring Boot (结合 Bean Validation / Hibernate Validator) 中,判断集合(List、Set、Map)不能为空且不为 null,最常用且语义最准确的注解是 @NotEmpty。
推荐写法
import jakarta.validation.constraints.NotEmpty; // Spring Boot 3.x
// import javax.validation.constraints.NotEmpty; // Spring Boot 2.x 及以下
public class OrderRequest {
@NotEmpty(message = "订单项ID集合不能为空")
private List<Long> orderItemIds;
// getter and setter...
}
为什么选 @NotEmpty?(与其他注解的对比)
| 注解 | 作用对象 | 行为描述 | 集合 [] (size=0) | 集合 null | 适用性 |
|---|---|---|---|---|---|
@NotEmpty | CharSequence, Collection, Map, Array | 非 null 且 size > 0 | ❌ 报错 (拦截) | ❌ 报错 (拦截) | ✅ 最佳选择 |
@NotNull | 任何对象 | 仅仅是非 null | ✅ 通过 (不拦截) | ❌ 报错 (拦截) | ❌ 不够用 (允许空集合) |
@Size(min=1) | Collection, Map, Array, String | size >= min | ❌ 报错 (拦截) | ✅ 通过 (通常视为有效,除非加@NotNull) | ⚠️ 也可以用,但语义不如 NotEmpty 清晰 |
@NotBlank | String (字符串) | 非 null 且包含非空格字符 | N/A | N/A | ❌ 仅限字符串,不能用于 List |
注意事项
-
依赖引入:
从 Spring Boot 2.3 开始,Validation 启动器被独立出来了,如果你的项目中注解无法导入,需要手动在pom.xml中添加:<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-validation</artifactId> </dependency> -
触发验证:
注解加上后,必须在 Controller 层的方法参数前加上@Valid或@Validated才会生效:@PostMapping("/create") public Result createOrder(@RequestBody @Valid OrderRequest request) { // ... }
总结:请直接使用 @NotEmpty。
不能为空且不为 null的注解使用&spm=1001.2101.3001.5002&articleId=155004936&d=1&t=3&u=2a57bfb86cd44a62a0f9e4bf89d02dbb)
2255

被折叠的 条评论
为什么被折叠?



