在 Java Web项目开发中,数据验证是一项至关重要的环节。Spring框架中的@Validated注解为我们提供了一种方便而强大的方式来实现数据验证。本文将详细介绍 @Validated 注解的用法及其在 Spring Boot 应用中的实践。
@Validated是 Spring 框架提供的用于数据验证的注解。它可用于方法参数、方法返回值以及类上。在基于SpringBoot开发的微服务项目中,类和方法上使用的频次是最高的。
@Validated注解通常与Java Bean Validation API(如 Hibernate Validator)一起使用,来定义验证规则。
<dependency>
<groupId>org.springframework.bootgroupId>
<artifactId>spring-boot-starter-validationartifactId>
dependency>
以下是一些常用的验证规则。
这里聊聊@NotNull、@NotEmpty和@NotBlank针对字符串处理的区别。
String s = "";
String s1;
String s2 = " ";
对于类变量s,使用@NotNull注解,不会拦截住,而使用@NotEmpty和@NotBlank注解会拦截住,因为s.length() = 0;
对于类变量s1,默认就为null,使用@NotNull、@NotEmpty和@NotBlank注解
都会被拦截住。
对于类变量s2,使用@NotNull和@NotEmpty注解
都不会被拦截住,因为s.length() > 0。而@NotBlank注解会拦住,因为有空格。
@Size(min = 3, max = 10)
private String userName;
@Size(min = 1, max = 3)
private List<String> phoneList;
@Size(min = 1, max = 10)
private int[] numbers;
@Pattern(regexp = "^1[3-9]\\d{9}$", message = "手机号码格式不正确")
private String phone;
// 常见的邮箱格式,包括用户名、@符号、域名等部分。
@Pattern(regexp = "^[a-zA-Z0-9_.-]+@[a-zA-Z0-9-]+(\\.[a-zA-Z0-9-]+)*\\.[a-zA-Z]{2,}$", message = "邮箱格式不正确")
private String email;
// 8-16位的密码,包含字母大小写、数字、特殊符号
@Pattern(regexp = "^(?=.*[a-zA-Z])(?=.*\\d)(?=.*[!@#$%^&*])[a-zA-Z\\d!@#$%^&*]{8,16}$", message = "密码格式不正确")
private String password;
假如,某零售品牌(某姆)有一个业务场景,需要手动录入并定期维护会员的信息。
会员的信息存储在vip_customer表中。表对应的实体类VipCustomer已经构建完成了,录入和更新都是基于该实体类来的。
录入会员信息的时候会员的手机号不能为空,更新的时候业务编码不能为空。那么,我们应该如何来设计验证规则呢?是的,大家都猜对了,采用分组。以下是示例代码。
// 1. 定义用户组
public interface CreateCustomerGroup{};
public interface UpdateCustomerGroup{};
// 2. 绑定组名和参数
public class VipCustomer{
@NotEmpty(message="业务编码不能为空", groups = UpdateCustomerGroup.class)
private String bizCode;
@NotEmpty(message = "会员手机号不能为空", groups = CreateCustomerGroup.class)
private String phone;
……
}
// 3. 在controller层使用@Validated注解并指定验证组
@RestController
@ResquestMapping("sam/vip/customer")
public class CustomerController{
@PutMapping("/add-customer")
Response<?> addCustomer(@ResquestBody @Validated(CreateCustomerGroup.class) VipCustomer vipCustomer){}
@PostMapping("/add-customer")
Response<?> updateCustomer(@ResquestBody @Validated(UpdateCustomerGroup.class) VipCustomer vipCustomer){}
}
在SpringBoot应用中,@Validated注解通常都会与@RestControllerAdvice结合使用,以实现全局的异常处理。
当数据验证失败时,就可以捕获MethodArgumentNotValidException和ConstraintViolationException异常,并返回自定义的错误信息给客户端。
下一节我们将结合最佳实践来剖析自定义验证规则,以及全局异常处理。