Spring Boot - 引入 validation 对参数或实体类进行校验不管用

发布时间 2023-08-29 13:30:01作者: Himmelbleu

版本说明

我的父工程版本号是 3.1.0。

file:[pom.xml]
<parent>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-parent</artifactId>
    <version>3.1.0</version>
    <relativePath/> <!-- lookup parent from repository -->
</parent>

这是 validation 的依赖:

file:[pom.xml - dependencies]
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-validation</artifactId>
</dependency>

@Validated

如果没有在需要校验的地方通过注解 @Validated 开启校验功能,也不会生效。

lit:[@Validated]:lit
@RestController("/api/auth")
public class AuthController {

}

参数

@GetMapping("/aks-mail-verify-code")
lit:[public Vo askMailVerifyCode(@Validated @RequestParam @Email(message = "不是一个合法的电子邮箱地址") String email,
                            @Validated @RequestParam @Pattern(regexp = "(register|login|reset)", message = "发送验证码的类型是 register 或 login 或 reset") String type,]:lit
                            HttpServletRequest http) {
    return mailRelatedService.getMailVerifyCode(email, type, HttpUtil.getIpAddr(http));
}

函数

lit:[@Validated]:lit
@GetMapping("/aks-mail-verify-code")
public Vo askMailVerifyCode(@RequestParam @Email(message = "不是一个合法的电子邮箱地址") String email,
                            @RequestParam @Pattern(regexp = "(register|login|reset)", message = "发送验证码的类型是 register 或 login 或 reset") String type,
                            HttpServletRequest http) {
    return mailRelatedService.getMailVerifyCode(email, type, HttpUtil.getIpAddr(http));
}

热加载的锅

如果你的 Idea 开启了热加载,引入包之后,需要重新编译再运行,也就是重启服务(不是重启 Idea 本身)。

编译并运行按钮