java - 带有 spring-boot-starter-validation 的 Spring Boot 验证不适用于 Spring Boot 版本 2.4.4

标签 java spring spring-boot validation

我试图在 Spring boot 中验证请求主体,但它不工作。目前我使用的是 Spring Boot 2.4.4 版本。这就是我所做的。

我添加了这个依赖spring-boot-starter-validation

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

具有导入验证功能的 Controller

import org.springframework.validation.annotation.Validated;
import javax.validation.Valid;

@RestController
@RequestMapping("api/administration")
@Validated
public class AdminController {

    @PostMapping("/create-organization")
    @PreAuthorize("hasAuthority('all:write')")
    public ResponseEntity createNewOrganization(
            @Valid @RequestBody OrganizationDto organization) {

        Organization response = adminService.createNewOrganization(organization);

        HttpHeaders headers = new HttpHeaders();
        headers.add("Location", "/api/organization/" + response.getId().toString());

        return new ResponseEntity(headers, HttpStatus.CREATED);
    }
}

组织目标

import javax.validation.constraints.NotBlank;
import javax.validation.constraints.NotEmpty;

@AllArgsConstructor
@NoArgsConstructor
@Getter
@Setter
@Builder
@ToString
public class OrganizationDto {

    @NotBlank
    @NotEmpty
    private String name;

    @NotBlank
    private String email;
}

我遇到的问题是当我从 Postman 发送以下正文时没有发生错误。

{
    "name": "",
    "email": ""
}

最佳答案

您的代码似乎是正确的,应该可以正常工作。所以在那之后我的建议是:

1)使用 mvn clean install 构建项目并尝试构建的 jar 以查看它是否有效

2)或者如果你从 Intelij 运行它

enter image description here

尝试刷新maven依赖,然后重新运行

我想你后来添加了依赖

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

它没有正确插入依赖项。

关于java - 带有 spring-boot-starter-validation 的 Spring Boot 验证不适用于 Spring Boot 版本 2.4.4,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67454378/

相关文章:

java.lang.ClassNotFoundException : org. springframework.core.ResolvableTypeProvider 问题

java - 关于简洁类模型/模式的建议,以解决方法中的多个细微变化

java - 如何使用Spring Boot将数据分离到两个表中?

maven - 在 intellij Idea 中运行 jmockit

java - 使用 RestTemplate 进行 RESTful 服务测试

java - 如何为 Android 5.0 构建我的纯 Java (Swing) 应用程序?

java - Spring-MVC:使用 'select-options' 时获取完整的对象而不是字符串

java - JSF 中不同组件的 ManagedBeans

java - 将许多第 3 方 jar 包含到一个简单的 spring boot 项目时会发生错误

java - 带有 gradle 的 camunda spring boot starter 导致 processEngineConfigurationImpl bean 丢失