有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java@valid annotation在spring boots中不起作用

我使用spring boot来构建API,在post请求中,我使用有效的符号来验证作为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;
    }

rest控制器类

@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;
    }

共 (2) 个答案

  1. # 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

  2. # 2 楼答案

    检查是否从验证中正确导入。不是来自com的约束。太阳伊斯塔克

    import javax.validation.constraints.NotNull;
    

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

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