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

SpringBoot 3.x中@NotEmpty注解无法解析问题求助

解决@NotEmpty注解无法解析的问题

核心原因

你遇到的问题是缺少Bean Validation相关依赖,javax.validation包下的注解需要引入对应的依赖库才能被识别。另外注意:Spring Boot 2.3版本之后,spring-boot-starter-web不再默认包含校验依赖,需要手动添加。

解决方案:添加对应依赖

根据你的项目类型修改build.gradle配置:

情况1:Spring Boot项目

在dependencies块中添加spring-boot-starter-validation依赖:

dependencies {
    // 保留你的原有依赖(比如spring-boot-starter-web等)
    implementation 'org.springframework.boot:spring-boot-starter-validation'
}

情况2:普通Spring项目(非Spring Boot)

需要同时添加API规范和校验引擎两个依赖:

dependencies {
    // Bean Validation API规范
    implementation 'javax.validation:validation-api:2.0.1.Final'
    // Hibernate Validator(业界常用的校验实现)
    implementation 'org.hibernate.validator:hibernate-validator:6.1.7.Final'
}

后续验证步骤

  1. 同步build.gradle,等待依赖下载完成
  2. 重新导入javax.validation.constraints.NotEmpty,此时注解和包路径应该能正常识别
  3. 在控制器层的方法参数前添加@Valid或@Validated注解,触发校验逻辑:
    @PostMapping("/customers")
    public ResponseEntity<String> addCustomer(@Valid @RequestBody Customer customer) {
        // 执行你的业务逻辑
        return ResponseEntity.ok("Customer added successfully");
    }
    

额外注意事项

  • 如果你的项目是Spring Boot 3.x及以上版本(基于Jakarta EE规范),需要将导入路径改为jakarta.validation.constraints.NotEmpty,依赖无需额外调整(spring-boot-starter-validation已适配Jakarta),此时导入语句应为:
    import jakarta.validation.constraints.NotEmpty;
    

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.21 21:03:10