验证器框架 @Min、@Max、@NotBlank 不工作

Validator Framework @Min, @Max, @NotBlank not working

我正在尝试验证器注解,但我似乎还没有掌握它

这些是我的 DTO

public class CustomerDTO {
    @NotBlank(message = "Blank")
    @Size(min = 3, max = 10, message = "error")
    @Pattern(regexp = "^[a-zA-Z0-9_]+", message = "Includes charectors not included")
    public String name;

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }
}
public class UserDTO {
    @NotBlank(message = "Blank")
    @Min(value = 3, message = "minimum len")
    @Max(value = 10, message = "max len")
    @Pattern(regexp = "^[a-zA-Z0-9_]+", message = "Includes charectors not included")
    public String name;

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }
}

这是我的控制器

@RestController
@RequestMapping(path = "/trial")
public class UserNameStringController {

    @PostMapping(path = "/nameChange")
    public void update(@Valid @RequestBody CustomerDTO customerDTO){
        System.out.println(customerDTO.getName());
        UserDTO userDTO = new UserDTO();
        userDTO.setName(customerDTO.getName());
        System.out.println(userDTO.getName());
    }
}

这是我的请求正文

{
   "name": "hi"
}

我能够得到一个有效的答案,它不会引发错误或发送我的错误消息。我不明白为什么???请有人帮忙

要做到这一点,您必须在配置中定义验证器 bean。

@Bean
public LocalValidatorFactoryBean validator() {
    LOGGER.info("Instatntiating Bean for Message Source ");
    LocalValidatorFactoryBean validatorFactoryBean = new LocalValidatorFactoryBean();
    ReloadableResourceBundleMessageSource messageSource = new ReloadableResourceBundleMessageSource();
    messageSource.setBasename("classpath:" + PROPERTY_PREFIX);
    validatorFactoryBean.setValidationMessageSource(messageSource);
    LOGGER.info("Instatntiating Bean for Message Source completed");
    return validatorFactoryBean;
}

在您的 pom.xml 中定义验证依赖项:

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