首页 > 解决方案 > @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;
    }

标签: javaspring-bootvalidation

解决方案


这个问题经常出现在最新版本的 spring boot(2.3.0) 中。

您需要添加以下依赖项:

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

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


推荐阅读