java spring boot 验证请求参数 spring boot @Valid 注解无效

java springboot validate request parameters springboot @Valid annotation is invalid

在DTO中为成员变量添加@NotBlank注解没有生效。是什么原因?请帮助我

首先检查此依赖项是否存在于 pom.xml 文件中。如果它不存在然后添加。 现在您的项目中存在依赖关系,可以使用@NotBlack 和@Valid 注释。

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency> 
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency> 
<dependency> 
    <groupId>com.h2database</groupId> 
    <artifactId>h2</artifactId>
    <version>1.4.197</version> 
    <scope>runtime</scope>
</dependency>
<dependency> 
    <groupId>org.springframework.boot</groupId> 
    <artifactId>spring-boot-starter-validation</artifactId> 
</dependency>

有关Validation in Spring Boot check this link

的更多信息

除了在依赖中包含 spring-boot-starter-validation 之外,您必须在控制器中的 @RequestBody 上包含 @Valid 注释,以便将 @NotBlank 注释应用于 DTO 中的成员变量。