@valid annotation在spring boots中不起作用



我使用spring boot来构建API,在后请求中,我使用Valid表示法来验证作为JSON文件发布的用户输入,但当我通过保留一些字段为空来测试它时,它们仍然会被传递。我不知道为什么,因为我在对象参数之前使用了有效的表示法。

可能出了什么问题?

对象类


@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

这取决于如何处理空值。如果将字符串字段留空意味着您将发送"这将被传递,因为它不是null值,因此Wolf类上的@NotNull注释不适用。

Michael

检查是否从Validation正确导入。非来自com.sun.istack.的约束

import javax.validation.constraints.NotNull;

如果这不能解决你的问题。如果您使用了验证依赖项,请检查您的pom.xml。

<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-validation</artifactId>
</dependency>

最新更新