You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Spring Boot中是否存在校验字段非空及空白字符的注解?

解决Spring Boot中JSON字段同时校验Null与空白字符的问题

嘿,这个需求太常见了!你现在用的@NotNull确实只能拦截null值,但对全是空格、制表符这类空白字符的字符串无能为力。好在Spring Boot依赖的Bean Validation规范里,有个专门的注解完美匹配你的需求——@NotBlank。

核心方案:使用@NotBlank注解

@NotBlank属于jakarta.validation.constraints(Spring Boot 3及以上版本)或javax.validation.constraints(Spring Boot 2版本)包,专门针对字符串类型字段,会同时校验三种情况:

  • 字段不能为null
  • 字段不能是空字符串""
  • 字段不能是仅由空白字符(空格、制表符、换行符等)组成的字符串

对比容易混淆的校验注解

为了避免踩坑,这里帮你理清几个常用校验注解的区别:

  • @NotNull:仅校验字段不为null,空字符串或全空白字符串会直接通过
  • @NotEmpty:校验字段不为null且长度大于0,所以空字符串""会被拦截,但全空白字符串(如" ")因为长度>0会通过
  • @NotBlank:正好覆盖你需要的所有场景,是最优解

代码示例

1. 定义带校验的请求实体类

// Spring Boot 3+ 引入包
import jakarta.validation.constraints.NotBlank;
// Spring Boot 2 引入包
// import javax.validation.constraints.NotBlank;

public class UserCreateRequest {
    @NotBlank(message = "用户名不能为null,也不能是空白字符")
    private String username;

    @NotBlank(message = "邮箱地址不能为null或空白字符")
    private String email;

    // 省略getter、setter、构造方法
}

2. 在Controller中启用校验

要让注解生效,需要在请求参数上添加@Valid(或@Validated,支持分组校验):

import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;
import jakarta.validation.Valid;

@RestController
public class UserController {
    @PostMapping("/users")
    public String createUser(@Valid @RequestBody UserCreateRequest request) {
        // 执行业务逻辑
        return "用户创建成功";
    }
}

特殊场景:自定义校验规则

如果你的需求更特殊(比如允许特定类型的空白字符),可以自定义校验注解和校验器,但绝大多数业务场景下,@NotBlank已经完全够用了。

内容的提问来源于stack exchange,提问作者Harsha

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.26 09:02:28