简体   繁体   English

Spring 引导 - 验证在使用 DTO 的 POST 上不起作用

[英]Spring Boot - Validation not working on POST with DTO

I'm having a problem.我有问题。 I try to validate the data passed to my DTO using the @Valid annotation and there is no result.我尝试使用 @Valid 注释验证传递给我的 DTO 的数据,但没有结果。 In the stack trace the data is normally inserted in the database.在堆栈跟踪中,数据通常插入到数据库中。 I expected at least one bad request.我预计至少有一个错误的要求。

At first I'm testing only in the POST method.起初我只在 POST 方法中进行测试。

Controller Controller

    @PostMapping
    public ResponseEntity<UserResponse> createUser(@Valid @RequestBody UserForm dto) {
        User userToAdd = dto.dtoToUser();
        userService.createUser(userToAdd);
        return new ResponseEntity<>(UserResponse.convertToDto(userToAdd), HttpStatus.CREATED);

    }

DTO DTO

public class UserForm {

    @NotBlank
    private String name;
    @CPF
    private String cpf;
    @Email
    private String email;
    @NotBlank
    private LocalDate birthDate;

    public UserForm(String name, String cpf, String email, LocalDate birthDate) {
        this.name = name;
        this.cpf = cpf;
        this.email = email;
        this.birthDate = birthDate;
    }

    public User dtoToUser() {
        return new User(this.name, this.email, this.cpf, this.birthDate);
    }

I ended up finding that removing a dependency from my pom.xml solved the problem.我最终发现从我的 pom.xml 中删除依赖项解决了这个问题。

Although I haven't imported this dependency into my project.虽然我还没有将这个依赖项导入到我的项目中。 It was causing some conflict and didn't give me any error in stacktrace.它引起了一些冲突,并且在堆栈跟踪中没有给我任何错误。

        <dependency>
            <groupId>org.hibernate</groupId>
            <artifactId>hibernate-validator</artifactId>
            <version>7.0.1.Final</version>
        </dependency>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM