java - @valid 注释在弹簧靴中不起作用
问题描述
我正在使用 spring boot 来构建 API,在发布请求中我使用 Valid 表示法来验证作为 JSON 文件发布的用户输入,但是当我通过将一些字段留空来测试它时,它们仍然通过。我不确定为什么,因为我在 object 参数之前使用了有效的符号。
有什么问题?
对象类
@NotNull(message = "Please provide a name")
private String name;
@NotNull(message = "Please provide a gender")
private Gender gender;
@NotNull(message = "Please provide a birthDay")
private String birthDay;
@NotNull(message = "Please provide a latitude")
private double latitude;
@NotNull(message = "Please provide a longitude")
private double longitude;
public Wolf(String id, @NotNull String name, @NotNull Gender gender, @NotNull String birthDay, @NotNull double latitude, @NotNull double longitude)
{
this.id = id!=null ? id : UUID.randomUUID().toString();
this.name= name;
this.gender= gender;
this.birthDay= birthDay;
this.latitude= latitude;
this.longitude= longitude;
}
休息控制器类
@Autowired
private Wolf_Service wolf_service;
@RequestMapping("Wolf/wolf_list")
public List<Wolf> All_wolfs()
{
return wolf_service.display_wolf_list();
}
@PostMapping(value = "Wolf/createwolf", consumes = "application/json", produces = "application/json")
public Wolf createwolf (@Valid @RequestBody Wolf wolf) {
var isAdded = wolf_service.add_wolf(wolf);
if (!isAdded) {
return null;
}
return wolf;
}
解决方案
这个问题经常出现在最新版本的 spring boot(2.3.0) 中。
您需要添加以下依赖项:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-validation</artifactId>
</dependency>
注意:您可以使用hibernate-validator
代替spring-boot-starter-validation
.
推荐阅读
- reactjs - React Native - 全局布尔值没有更新?
- javascript - 我可以显示所有堆叠系列的总数 - 堆叠分组 highchart - Highcharts
- java - S3 并发写入行为
- android - 为 com.google.common.util.concurrent.SettableFuture@65b91722[status=PENDING] 等待了 2 分钟(加上 5249400 纳秒延迟)
- css - 使用外部样式表时,Chrome 在页面加载时从默认属性值转换为指定值
- flutter - 我们可以用抽屉按钮控制颤动标签的位置吗
- json - 如何在不丢失类型的情况下将 JSON 从函数解组为空结构?
- git - 尝试使用 Github Actions 复制 repo 时出现身份验证错误
- spring-boot - 无法部署我的第一个 Azure Spring Cloud 应用程序
- node.js - Date-fns 格式化日期?