本文会详细介绍Spring Validation各类场景下的最佳实践及其实现原理,死磕到底!
项目源码:spring-validationjava
Java API规范(JSR303)定义了Bean校验的标准validation-api,但没有提供实现。hibernate validation是对这个规范的实现,并增长了校验注解如@Email、@Length等。Spring Validation是对hibernate validation的二次封装,用于支持spring mvc参数自动校验。接下来,咱们以spring-boot项目为例,介绍Spring Validation的使用。web
若是spring-boot版本小于2.3.x,spring-boot-starter-web会自动传入hibernate-validator依赖。若是spring-boot版本大于2.3.x,则须要手动引入依赖:面试
<dependency> <groupId>org.hibernate</groupId> <artifactId>hibernate-validator</artifactId> <version>6.0.1.Final</version> </dependency>
对于web服务来讲,为防止非法参数对业务形成影响,在Controller层必定要作参数校验的!大部分状况下,请求参数分为以下两种形式:spring
1.POST、PUT请求,使用requestBody传递参数;编程
2.GET请求,使用requestParam/PathVariable传递参数。json
下面咱们简单介绍下requestBody和requestParam/PathVariable的参数校验实战!后端
POST、PUT请求通常会使用requestBody传递参数,这种状况下,后端使用DTO对象进行接收。只要给DTO对象加上@Validated注解就能实现自动参数校验。好比,有一个保存User的接口,要求userName长度是2-10,account和password字段长度是6-20。若是校验失败,会抛出MethodArgumentNotValidException异常,Spring默认会将其转为400(Bad Request)请求。api
DTO表示数据传输对象(Data Transfer Object),用于服务器和客户端之间交互传输使用的。在spring-web项目中能够表示用于接收请求参数的Bean对象。数组
在DTO字段上声明约束注解spring-mvc
@Data public class UserDTO { private Long userId; @NotNull @Length(min = 2, max = 10) private String userName; @NotNull @Length(min = 6, max = 20) private String account; @NotNull @Length(min = 6, max = 20) private String password; }
在方法参数上声明校验注解
@PostMapping("/save") public Result saveUser(@RequestBody @Validated UserDTO userDTO) { // 校验经过,才会执行业务逻辑处理 return Result.ok(); }
这种状况下,使用@Valid和@Validated均可以。
GET请求通常会使用requestParam/PathVariable传参。若是参数比较多(好比超过6个),仍是推荐使用DTO对象接收。不然,推荐将一个个参数平铺到方法入参中。在这种状况下,必须在Controller类上标注@Validated注解,并在入参上声明约束注解(如@Min等)。若是校验失败,会抛出ConstraintViolationException异常。代码示例以下:
@RequestMapping("/api/user") @RestController @Validated public class UserController { // 路径变量 @GetMapping("{userId}") public Result detail(@PathVariable("userId") @Min(10000000000000000L) Long userId) { // 校验经过,才会执行业务逻辑处理 UserDTO userDTO = new UserDTO(); userDTO.setUserId(userId); userDTO.setAccount("11111111111111111"); userDTO.setUserName("xixi"); userDTO.setAccount("11111111111111111"); return Result.ok(userDTO); } // 查询参数 @GetMapping("getByAccount") public Result getByAccount(@Length(min = 6, max = 20) @NotNull String account) { // 校验经过,才会执行业务逻辑处理 UserDTO userDTO = new UserDTO(); userDTO.setUserId(10000000000000003L); userDTO.setAccount(account); userDTO.setUserName("xixi"); userDTO.setAccount("11111111111111111"); return Result.ok(userDTO); } }
前面说过,若是校验失败,会抛出MethodArgumentNotValidException或者ConstraintViolationException异常。在实际项目开发中,一般会用统一异常处理来返回一个更友好的提示。好比咱们系统要求不管发送什么异常,http的状态码必须返回200,由业务码去区分系统的异常状况。
@RestControllerAdvice public class CommonExceptionHandler { @ExceptionHandler({MethodArgumentNotValidException.class}) @ResponseStatus(HttpStatus.OK) @ResponseBody public Result handleMethodArgumentNotValidException(MethodArgumentNotValidException ex) { BindingResult bindingResult = ex.getBindingResult(); StringBuilder sb = new StringBuilder("校验失败:"); for (FieldError fieldError : bindingResult.getFieldErrors()) { sb.append(fieldError.getField()).append(":").append(fieldError.getDefaultMessage()).append(", "); } String msg = sb.toString(); return Result.fail(BusinessCode.参数校验失败, msg); } @ExceptionHandler({ConstraintViolationException.class}) @ResponseStatus(HttpStatus.OK) @ResponseBody public Result handleConstraintViolationException(ConstraintViolationException ex) { return Result.fail(BusinessCode.参数校验失败, ex.getMessage()); } }
在实际项目中,可能多个方法须要使用同一个DTO类来接收参数,而不一样方法的校验规则极可能是不同的。这个时候,简单地在DTO类的字段上加约束注解没法解决这个问题。所以,spring-validation支持了分组校验的功能,专门用来解决这类问题。仍是上面的例子,好比保存User的时候,UserId是可空的,可是更新User的时候,UserId的值必须>=10000000000000000L;其它字段的校验规则在两种状况下同样。
这个时候使用分组校验的代码示例以下:
@Data public class UserDTO { @Min(value = 10000000000000000L, groups = Update.class) private Long userId; @NotNull(groups = {Save.class, Update.class}) @Length(min = 2, max = 10, groups = {Save.class, Update.class}) private String userName; @NotNull(groups = {Save.class, Update.class}) @Length(min = 6, max = 20, groups = {Save.class, Update.class}) private String account; @NotNull(groups = {Save.class, Update.class}) @Length(min = 6, max = 20, groups = {Save.class, Update.class}) private String password; /** * 保存的时候校验分组 */ public interface Save { } /** * 更新的时候校验分组 */ public interface Update { } }
@PostMapping("/save") public Result saveUser(@RequestBody @Validated(UserDTO.Save.class) UserDTO userDTO) { // 校验经过,才会执行业务逻辑处理 return Result.ok(); } @PostMapping("/update") public Result updateUser(@RequestBody @Validated(UserDTO.Update.class) UserDTO userDTO) { // 校验经过,才会执行业务逻辑处理 return Result.ok(); }
前面的示例中,DTO类里面的字段都是基本数据类型和String类型。可是实际场景中,有可能某个字段也是一个对象,这种状况先,可使用嵌套校验。好比,上面保存User信息的时候同时还带有Job信息。须要注意的是,此时DTO类的对应字段必须标记@Valid注解。
@Data public class UserDTO { @Min(value = 10000000000000000L, groups = Update.class) private Long userId; @NotNull(groups = {Save.class, Update.class}) @Length(min = 2, max = 10, groups = {Save.class, Update.class}) private String userName; @NotNull(groups = {Save.class, Update.class}) @Length(min = 6, max = 20, groups = {Save.class, Update.class}) private String account; @NotNull(groups = {Save.class, Update.class}) @Length(min = 6, max = 20, groups = {Save.class, Update.class}) private String password; @NotNull(groups = {Save.class, Update.class}) @Valid private Job job; @Data public static class Job { @Min(value = 1, groups = Update.class) private Long jobId; @NotNull(groups = {Save.class, Update.class}) @Length(min = 2, max = 10, groups = {Save.class, Update.class}) private String jobName; @NotNull(groups = {Save.class, Update.class}) @Length(min = 2, max = 10, groups = {Save.class, Update.class}) private String position; } /** * 保存的时候校验分组 */ public interface Save { } /** * 更新的时候校验分组 */ public interface Update { } }
嵌套校验能够结合分组校验一块儿使用。还有就是嵌套集合校验会对集合里面的每一项都进行校验,例如List
若是请求体直接传递了json数组给后台,并但愿对数组中的每一项都进行参数校验。此时,若是咱们直接使用java.util.Collection下的list或者set来接收数据,参数校验并不会生效!咱们可使用自定义list集合来接收参数:
public class ValidationList<E> implements List<E> { @Delegate // @Delegate是lombok注解 @Valid // 必定要加@Valid注解 public List<E> list = new ArrayList<>(); // 必定要记得重写toString方法 @Override public String toString() { return list.toString(); } }
@Delegate注解受lombok版本限制,1.18.6以上版本可支持。若是校验不经过,会抛出NotReadablePropertyException,一样可使用统一异常进行处理。
好比,咱们须要一次性保存多个User对象,Controller层的方法能够这么写:
@PostMapping("/saveList") public Result saveList(@RequestBody @Validated(UserDTO.Save.class) ValidationList<UserDTO> userList) { // 校验经过,才会执行业务逻辑处理 return Result.ok(); }
业务需求老是比框架提供的这些简单校验要复杂的多,咱们能够自定义校验来知足咱们的需求。自定义spring validation很是简单,假设咱们自定义加密id(由数字或者a-f的字母组成,32-256长度)校验,主要分为两步:
@Target({METHOD, FIELD, ANNOTATION_TYPE, CONSTRUCTOR, PARAMETER}) @Retention(RUNTIME) @Documented @Constraint(validatedBy = {EncryptIdValidator.class}) public @interface EncryptId { // 默认错误消息 String message() default "加密id格式错误"; // 分组 Class<?>[] groups() default {}; // 负载 Class<? extends Payload>[] payload() default {}; }
public class EncryptIdValidator implements ConstraintValidator<EncryptId, String> { private static final Pattern PATTERN = Pattern.compile("^[a-f\\d]{32,256}$"); @Override public boolean isValid(String value, ConstraintValidatorContext context) { // 不为null才进行校验 if (value != null) { Matcher matcher = PATTERN.matcher(value); return matcher.find(); } return true; } }
这样咱们就可使用@EncryptId进行参数校验了!
上面的示例都是基于注解来实现自动校验的,在某些状况下,咱们可能但愿以编程方式调用验证。这个时候能够注入javax.validation.Validator对象,而后再调用其api。
@Autowired private javax.validation.Validator globalValidator; // 编程式校验 @PostMapping("/saveWithCodingValidate") public Result saveWithCodingValidate(@RequestBody UserDTO userDTO) { Set<ConstraintViolation<UserDTO>> validate = globalValidator.validate(userDTO, UserDTO.Save.class); // 若是校验经过,validate为空;不然,validate包含未校验经过项 if (validate.isEmpty()) { // 校验经过,才会执行业务逻辑处理 } else { for (ConstraintViolation<UserDTO> userDTOConstraintViolation : validate) { // 校验失败,作其它逻辑 System.out.println(userDTOConstraintViolation); } } return Result.ok(); }
Spring Validation默认会校验完全部字段,而后才抛出异常。能够经过一些简单的配置,开启Fali Fast模式,一旦校验失败就当即返回。
@Bean public Validator validator() { ValidatorFactory validatorFactory = Validation.byProvider(HibernateValidator.class) .configure() // 快速失败模式 .failFast(true) .buildValidatorFactory(); return validatorFactory.getValidator(); }
@Valid和@Validated区别
在spring-mvc中,RequestResponseBodyMethodProcessor是用于解析@RequestBody标注的参数以及处理@ResponseBody标注方法的返回值的。显然,执行参数校验的逻辑确定就在解析参数的方法resolveArgument()中:
public class RequestResponseBodyMethodProcessor extends AbstractMessageConverterMethodProcessor { @Override public Object resolveArgument(MethodParameter parameter, @Nullable ModelAndViewContainer mavContainer, NativeWebRequest webRequest, @Nullable WebDataBinderFactory binderFactory) throws Exception { parameter = parameter.nestedIfOptional(); //将请求数据封装到DTO对象中 Object arg = readWithMessageConverters(webRequest, parameter, parameter.getNestedGenericParameterType()); String name = Conventions.getVariableNameForParameter(parameter); if (binderFactory != null) { WebDataBinder binder = binderFactory.createBinder(webRequest, arg, name); if (arg != null) { // 执行数据校验 validateIfApplicable(binder, parameter); if (binder.getBindingResult().hasErrors() && isBindExceptionRequired(binder, parameter)) { throw new MethodArgumentNotValidException(parameter, binder.getBindingResult()); } } if (mavContainer != null) { mavContainer.addAttribute(BindingResult.MODEL_KEY_PREFIX + name, binder.getBindingResult()); } } return adaptArgumentIfNecessary(arg, parameter); } }
能够看到,resolveArgument()调用了validateIfApplicable()进行参数校验。
protected void validateIfApplicable(WebDataBinder binder, MethodParameter parameter) { // 获取参数注解,好比@RequestBody、@Valid、@Validated Annotation[] annotations = parameter.getParameterAnnotations(); for (Annotation ann : annotations) { // 先尝试获取@Validated注解 Validated validatedAnn = AnnotationUtils.getAnnotation(ann, Validated.class); //若是直接标注了@Validated,那么直接开启校验。 //若是没有,那么判断参数前是否有Valid起头的注解。 if (validatedAnn != null || ann.annotationType().getSimpleName().startsWith("Valid")) { Object hints = (validatedAnn != null ? validatedAnn.value() : AnnotationUtils.getValue(ann)); Object[] validationHints = (hints instanceof Object[] ? (Object[]) hints : new Object[] {hints}); //执行校验 binder.validate(validationHints); break; } } }
看到这里,你们应该能明白为何这种场景下@Validated、@Valid两个注解能够混用。咱们接下来继续看WebDataBinder.validate()实现。
@Override public void validate(Object target, Errors errors, Object... validationHints) { if (this.targetValidator != null) { processConstraintViolations( //此处调用Hibernate Validator执行真正的校验 this.targetValidator.validate(target, asValidationGroups(validationHints)), errors); } }
最终发现底层最终仍是调用了Hibernate Validator进行真正的校验处理。
上面提到的将参数一个个平铺到方法参数中,而后在每一个参数前面声明约束注解的校验方式,就是方法级别的参数校验。实际上,这种方式可用于任何Spring Bean的方法上,好比Controller/Service等。其底层实现原理就是AOP,具体来讲是经过MethodValidationPostProcessor动态注册AOP切面,而后使用MethodValidationInterceptor对切点方法织入加强。
public class MethodValidationPostProcessor extends AbstractBeanFactoryAwareAdvisingPostProcessorimplements InitializingBean { @Override public void afterPropertiesSet() { //为全部`@Validated`标注的Bean建立切面 Pointcut pointcut = new AnnotationMatchingPointcut(this.validatedAnnotationType, true); //建立Advisor进行加强 this.advisor = new DefaultPointcutAdvisor(pointcut, createMethodValidationAdvice(this.validator)); } //建立Advice,本质就是一个方法拦截器 protected Advice createMethodValidationAdvice(@Nullable Validator validator) { return (validator != null ? new MethodValidationInterceptor(validator) : new MethodValidationInterceptor()); } }
接着看一下MethodValidationInterceptor:
public class MethodValidationInterceptor implements MethodInterceptor { @Override public Object invoke(MethodInvocation invocation) throws Throwable { //无需加强的方法,直接跳过 if (isFactoryBeanMetadataMethod(invocation.getMethod())) { return invocation.proceed(); } //获取分组信息 Class<?>[] groups = determineValidationGroups(invocation); ExecutableValidator execVal = this.validator.forExecutables(); Method methodToValidate = invocation.getMethod(); Set<ConstraintViolation<Object>> result; try { //方法入参校验,最终仍是委托给Hibernate Validator来校验 result = execVal.validateParameters( invocation.getThis(), methodToValidate, invocation.getArguments(), groups); } catch (IllegalArgumentException ex) { ... } //有异常直接抛出 if (!result.isEmpty()) { throw new ConstraintViolationException(result); } //真正的方法调用 Object returnValue = invocation.proceed(); //对返回值作校验,最终仍是委托给Hibernate Validator来校验 result = execVal.validateReturnValue(invocation.getThis(), methodToValidate, returnValue, groups); //有异常直接抛出 if (!result.isEmpty()) { throw new ConstraintViolationException(result); } return returnValue; } }
实际上,不论是requestBody参数校验仍是方法级别的校验,最终都是调用Hibernate Validator执行校验,Spring Validation只是作了一层封装。
我这边整理了一份:Spring相关资料文档以及知识图谱、Java的系统化资料,(包括Java核心知识点、面试专题和20年最新的互联网真题、电子书等)有须要的朋友能够关注公众号【程序媛小琬】便可获取。