首页 > 解决方案 > 验证 bean 在 Java 11 和 spring boot 2.5.3 中不起作用

问题描述

您好,在花费数小时阅读 stackoverflow 答案并试图找到答案之后,我仍然无法找出为什么验证器(例如NotNullNotBlank不能在 java 中工作)。我仍然可以使用空白名称发送帖子请求。该项目在 Java 11 和 Spring boot starter v2.5.3 上。非常感谢你,如果你能弄清楚,我觉得我必须给你买一个冰淇淋:')

在我的模型中:

import javax.validation.constraints.NotBlank;

@NotBlank
private final String name;

在我的控制器中:

import javax.validation.Valid;
import javax.validation.constraints.NotNull;

    @PostMapping(path="add")
    public void addUser(@Valid @NotNull @RequestBody User user) {
        //Request body takes the data taken and converts it into a User
        userService.addUser(user);
    }

    @PutMapping(path="user/{id}")
    public void updateUser(@PathVariable("id") UUID id, @Valid @NotNull @RequestBody User userToUpdate) {
        userService.updateUser(id, userToUpdate);
    }

在我的依赖项中pom.xml

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-validation</artifactId>
        </dependency>
        <dependency>
            <groupId>javax.validation</groupId>
            <artifactId>validation-api</artifactId>
        </dependency>
    </dependencies>

标签: javaspring-boot

解决方案


推荐阅读