@valid注释在春季靴子中不起作用

时间:2020-10-27 15:31:37

标签: java spring-boot validation

我正在使用Spring Boot来构建API,在发布请求中,我使用有效表示法来验证发布为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;
    }

3 个答案:

答案 0 :(得分:1)

此问题通常出现在最新版本的spring boot(2.3.0)中。

您需要添加以下依赖项:

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

注意您可以使用hibernate-validator代替spring-boot-starter-validation

答案 1 :(得分:0)

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

迈克尔

答案 2 :(得分:0)

检查是否从Validation正确导入。约束不是从com.sun.istack导入。

import javax.validation.constraints.NotNull;

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

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