概述

我们公司项目中的参数校验非常的混乱,绝大部分都是手动编码对参数一个个校验,导致代码十分臃肿庞大。所以,网上搜了下这个很流行的Validator框架,非常的简洁方便。这个小伙伴的这篇文章写的很全面,SpringBoot参数校验——Validator框架, 如何使用我就不复述了,现在它的源码实现做一个简单的整理总结。

源码解析

执行流程

这是一个springmvc的应用,请求进来,通过DispatcherServlet类转发,最终调到RequestResponseBodyMethodProcessor类的resolveArgument()方法。
image.png
首先查看RequestResponseBodyMethodProcessorresolveArgument()方法。

  1. public class RequestResponseBodyMethodProcessor extends AbstractMessageConverterMethodProcessor {
  2. @Override
  3. public Object resolveArgument(MethodParameter parameter, @Nullable ModelAndViewContainer mavContainer,
  4. NativeWebRequest webRequest, @Nullable WebDataBinderFactory binderFactory) throws Exception {
  5. parameter = parameter.nestedIfOptional();
  6. // 将请求数据转换到对象中
  7. Object arg = readWithMessageConverters(webRequest, parameter, parameter.getNestedGenericParameterType());
  8. String name = Conventions.getVariableNameForParameter(parameter);
  9. if (binderFactory != null) {
  10. // 创建参数绑定器
  11. WebDataBinder binder = binderFactory.createBinder(webRequest, arg, name);
  12. if (arg != null) {
  13. // 核心操作,执行数据参数
  14. validateIfApplicable(binder, parameter);
  15. if (binder.getBindingResult().hasErrors() && isBindExceptionRequired(binder, parameter)) {
  16. throw new MethodArgumentNotValidException(parameter, binder.getBindingResult());
  17. }
  18. }
  19. if (mavContainer != null) {
  20. mavContainer.addAttribute(BindingResult.MODEL_KEY_PREFIX + name, binder.getBindingResult());
  21. }
  22. }
  23. return adaptArgumentIfNecessary(arg, parameter);
  24. }
  25. }

关键方法validateIfApplicable()中进行数据校验。

  1. protected void validateIfApplicable(WebDataBinder binder, MethodParameter parameter) {
  2. // 获取参数上绑定的注解,如@Valid, @Validated等
  3. Annotation[] annotations = parameter.getParameterAnnotations();
  4. // 遍历注解
  5. for (Annotation ann : annotations) {
  6. // 关键方法,判断是否进行数据校验
  7. Object[] validationHints = ValidationAnnotationUtils.determineValidationHints(ann);
  8. // 如果数据校验注解不为空,开启后续的校验流程
  9. if (validationHints != null) {
  10. binder.validate(validationHints);
  11. break;
  12. }
  13. }
  14. }

看下ValidationAnnotationUtils.determineValidationHints()

  1. @Nullable
  2. public static Object[] determineValidationHints(Annotation ann) {
  3. Class<? extends Annotation> annotationType = ann.annotationType();
  4. String annotationName = annotationType.getName();
  5. // 判断注解名称是否为Valid
  6. if ("javax.validation.Valid".equals(annotationName)) {
  7. return EMPTY_OBJECT_ARRAY;
  8. }
  9. // 判断注解是否是Validated
  10. Validated validatedAnn = AnnotationUtils.getAnnotation(ann, Validated.class);
  11. if (validatedAnn != null) {
  12. Object hints = validatedAnn.value();
  13. return convertValidationHints(hints);
  14. }
  15. // 判断注解是否是以Valid开头
  16. if (annotationType.getSimpleName().startsWith("Valid")) {
  17. Object hints = AnnotationUtils.getValue(ann);
  18. return convertValidationHints(hints);
  19. }
  20. // 返回空,表示不需要进行校验
  21. return null;
  22. }

所以看到,最终程序兼容了@Valid@Validated注解,他们都会开启参数校验。接着就要开启校验流程了,最终方法走到了SpringValidatorAdapter#validate()

  1. @Override
  2. public void validate(Object target, Errors errors) {
  3. if (this.targetValidator != null) {
  4. // 调用数据校验工作,这里的targetValidator是hibernate-validator中ValidatorImpl类
  5. processConstraintViolations(this.targetValidator.validate(target), errors);
  6. }
  7. }

走到了ValidatorImpl#validate方法

  1. // 该方法主要用于开启校验的一些准备巩固走
  2. @Override
  3. public final <T> Set<ConstraintViolation<T>> validate(T object, Class<?>... groups) {
  4. Contracts.assertNotNull( object, MESSAGES.validatedObjectMustNotBeNull() );
  5. sanityCheckGroups( groups );
  6. @SuppressWarnings("unchecked")
  7. Class<T> rootBeanClass = (Class<T>) object.getClass();
  8. BeanMetaData<T> rootBeanMetaData = beanMetaDataManager.getBeanMetaData( rootBeanClass );
  9. if ( !rootBeanMetaData.hasConstraints() ) {
  10. return Collections.emptySet();
  11. }
  12. // 获取验证的上下文,主要就是获取@NotNull, @Max等校验数据
  13. BaseBeanValidationContext<T> validationContext = getValidationContextBuilder().forValidate( rootBeanClass, rootBeanMetaData, object );
  14. ValidationOrder validationOrder = determineGroupValidationOrder( groups );
  15. // 创建请求参数数据上下文
  16. BeanValueContext<?, Object> valueContext = ValueContexts.getLocalExecutionContextForBean(
  17. validatorScopedContext.getParameterNameProvider(),
  18. object,
  19. validationContext.getRootBeanMetaData(),
  20. PathImpl.createRootPath()
  21. );
  22. // 开始校验
  23. return validateInContext( validationContext, valueContext, validationOrder );
  24. }
  25. // 该方法是使用校验的上下文信息进行数据校验工作
  26. private <T, U> Set<ConstraintViolation<T>> validateInContext(BaseBeanValidationContext<T> validationContext, BeanValueContext<U, Object> valueContext,
  27. ValidationOrder validationOrder) {
  28. if ( valueContext.getCurrentBean() == null ) {
  29. return Collections.emptySet();
  30. }
  31. BeanMetaData<U> beanMetaData = valueContext.getCurrentBeanMetaData();
  32. if ( beanMetaData.isDefaultGroupSequenceRedefined() ) {
  33. validationOrder.assertDefaultGroupSequenceIsExpandable( beanMetaData.getDefaultGroupSequence( valueContext.getCurrentBean() ) );
  34. }
  35. // 处理单个组的校验,也就是最简单的那种校验逻辑
  36. Iterator<Group> groupIterator = validationOrder.getGroupIterator();
  37. while ( groupIterator.hasNext() ) {
  38. Group group = groupIterator.next();
  39. valueContext.setCurrentGroup( group.getDefiningClass() );
  40. validateConstraintsForCurrentGroup( validationContext, valueContext );
  41. if ( shouldFailFast( validationContext ) ) {
  42. return validationContext.getFailingConstraints();
  43. }
  44. }
  45. // 执行有级联约束的校验
  46. groupIterator = validationOrder.getGroupIterator();
  47. while ( groupIterator.hasNext() ) {
  48. Group group = groupIterator.next();
  49. valueContext.setCurrentGroup( group.getDefiningClass() );
  50. validateCascadedConstraints( validationContext, valueContext );
  51. if ( shouldFailFast( validationContext ) ) {
  52. return validationContext.getFailingConstraints();
  53. }
  54. }
  55. Iterator<Sequence> sequenceIterator = validationOrder.getSequenceIterator();
  56. while ( sequenceIterator.hasNext() ) {
  57. Sequence sequence = sequenceIterator.next();
  58. for ( GroupWithInheritance groupOfGroups : sequence ) {
  59. int numberOfViolations = validationContext.getFailingConstraints().size();
  60. for ( Group group : groupOfGroups ) {
  61. valueContext.setCurrentGroup( group.getDefiningClass() );
  62. validateConstraintsForCurrentGroup( validationContext, valueContext );
  63. if ( shouldFailFast( validationContext ) ) {
  64. return validationContext.getFailingConstraints();
  65. }
  66. validateCascadedConstraints( validationContext, valueContext );
  67. if ( shouldFailFast( validationContext ) ) {
  68. return validationContext.getFailingConstraints();
  69. }
  70. }
  71. if ( validationContext.getFailingConstraints().size() > numberOfViolations ) {
  72. break;
  73. }
  74. }
  75. }
  76. return validationContext.getFailingConstraints();
  77. }

我们关注在普通的数据校验处理validateConstraintsForCurrentGroup()方法。

  1. private void validateConstraintsForCurrentGroup(BaseBeanValidationContext<?> validationContext, BeanValueContext<?, Object> valueContext) {
  2. // we are not validating the default group there is nothing special to consider. If we are validating the default
  3. // group sequence we have to consider that a class in the hierarchy could redefine the default group sequence.
  4. // 如果不是默认分组的情况
  5. if ( !valueContext.validatingDefault() ) {
  6. validateConstraintsForNonDefaultGroup( validationContext, valueContext );
  7. }
  8. // 如果是默认分组的情况
  9. else {
  10. validateConstraintsForDefaultGroup( validationContext, valueContext );
  11. }
  12. }
  13. private <U> void validateConstraintsForDefaultGroup(BaseBeanValidationContext<?> validationContext, BeanValueContext<U, Object> valueContext) {
  14. final BeanMetaData<U> beanMetaData = valueContext.getCurrentBeanMetaData();
  15. final Map<Class<?>, Class<?>> validatedInterfaces = new HashMap<>();
  16. // evaluating the constraints of a bean per class in hierarchy, this is necessary to detect potential default group re-definitions
  17. for ( Class<? super U> clazz : beanMetaData.getClassHierarchy() ) {
  18. BeanMetaData<? super U> hostingBeanMetaData = beanMetaDataManager.getBeanMetaData( clazz );
  19. boolean defaultGroupSequenceIsRedefined = hostingBeanMetaData.isDefaultGroupSequenceRedefined();
  20. // if the current class redefined the default group sequence, this sequence has to be applied to all the class hierarchy.
  21. if ( defaultGroupSequenceIsRedefined ) {
  22. Iterator<Sequence> defaultGroupSequence = hostingBeanMetaData.getDefaultValidationSequence( valueContext.getCurrentBean() );
  23. Set<MetaConstraint<?>> metaConstraints = hostingBeanMetaData.getMetaConstraints();
  24. while ( defaultGroupSequence.hasNext() ) {
  25. for ( GroupWithInheritance groupOfGroups : defaultGroupSequence.next() ) {
  26. boolean validationSuccessful = true;
  27. for ( Group defaultSequenceMember : groupOfGroups ) {
  28. validationSuccessful = validateConstraintsForSingleDefaultGroupElement( validationContext, valueContext, validatedInterfaces, clazz,
  29. metaConstraints, defaultSequenceMember ) && validationSuccessful;
  30. }
  31. validationContext.markCurrentBeanAsProcessed( valueContext );
  32. if ( !validationSuccessful ) {
  33. break;
  34. }
  35. }
  36. }
  37. }
  38. // fast path in case the default group sequence hasn't been redefined
  39. else {
  40. Set<MetaConstraint<?>> metaConstraints = hostingBeanMetaData.getDirectMetaConstraints();
  41. // 执行校验操作
  42. validateConstraintsForSingleDefaultGroupElement( validationContext, valueContext, validatedInterfaces, clazz, metaConstraints,
  43. Group.DEFAULT_GROUP );
  44. validationContext.markCurrentBeanAsProcessed( valueContext );
  45. }
  46. // all constraints in the hierarchy has been validated, stop validation.
  47. if ( defaultGroupSequenceIsRedefined ) {
  48. break;
  49. }
  50. }
  51. }

最关键的方法是在validateConstraintsForSingleDefaultGroupElement()方法中执行最终的数据校验,大家通过断点一步一步下去,最终发现走到了SimpleConstraintTree#validateConstraints()

  1. @Override
  2. protected void validateConstraints(ValidationContext<?> validationContext,
  3. ValueContext<?, ?> valueContext,
  4. Collection<ConstraintValidatorContextImpl> violatedConstraintValidatorContexts) {
  5. if ( LOG.isTraceEnabled() ) {
  6. LOG.tracef(
  7. "Validating value %s against constraint defined by %s.",
  8. valueContext.getCurrentValidatedValue(),
  9. descriptor
  10. );
  11. }
  12. // find the right constraint validator
  13. ConstraintValidator<B, ?> validator = getInitializedConstraintValidator( validationContext, valueContext );
  14. // create a constraint validator context
  15. ConstraintValidatorContextImpl constraintValidatorContext = validationContext.createConstraintValidatorContextFor(
  16. descriptor, valueContext.getPropertyPath()
  17. );
  18. // validate, 进行单个校验
  19. if ( validateSingleConstraint( valueContext, constraintValidatorContext, validator ).isPresent() ) {
  20. violatedConstraintValidatorContexts.add( constraintValidatorContext );
  21. }
  22. }
  23. protected final <V> Optional<ConstraintValidatorContextImpl> validateSingleConstraint(
  24. ValueContext<?, ?> valueContext,
  25. ConstraintValidatorContextImpl constraintValidatorContext,
  26. ConstraintValidator<A, V> validator) {
  27. boolean isValid;
  28. try {
  29. @SuppressWarnings("unchecked")
  30. V validatedValue = (V) valueContext.getCurrentValidatedValue();
  31. // 执行各个校验器的校验方法,validator是一个接口,有很多具体校验的实现方法
  32. isValid = validator.isValid( validatedValue, constraintValidatorContext );
  33. }
  34. catch (RuntimeException e) {
  35. if ( e instanceof ConstraintDeclarationException ) {
  36. throw e;
  37. }
  38. throw LOG.getExceptionDuringIsValidCallException( e );
  39. }
  40. if ( !isValid ) {
  41. //We do not add these violations yet, since we don't know how they are
  42. //going to influence the final boolean evaluation
  43. return Optional.of( constraintValidatorContext );
  44. }
  45. return Optional.empty();
  46. }

上面就是整个请求参数的校验流程。

初始化设置hibernate-validator

大家有没有想过请求数据的校验,为什么会选择hibernate-validator作为校验器,它又是在什么时候设置呢?我们从源码的角度看看。

ValidationAutoConfiguration

因为我们引入了spring-boot-starter-validation,开启了自动装配,可以看到有个ValidationAutoConfiguration类。

  1. @AutoConfiguration
  2. @ConditionalOnClass(ExecutableValidator.class)
  3. @ConditionalOnResource(resources = "classpath:META-INF/services/javax.validation.spi.ValidationProvider")
  4. @Import(PrimaryDefaultValidatorPostProcessor.class)
  5. public class ValidationAutoConfiguration {
  6. // 创建默认的defaultValidator
  7. @Bean
  8. @Role(BeanDefinition.ROLE_INFRASTRUCTURE)
  9. @ConditionalOnMissingBean(Validator.class)
  10. public static LocalValidatorFactoryBean defaultValidator(ApplicationContext applicationContext) {
  11. LocalValidatorFactoryBean factoryBean = new LocalValidatorFactoryBean();
  12. MessageInterpolatorFactory interpolatorFactory = new MessageInterpolatorFactory(applicationContext);
  13. factoryBean.setMessageInterpolator(interpolatorFactory.getObject());
  14. return factoryBean;
  15. }
  16. @Bean
  17. @ConditionalOnMissingBean(search = SearchStrategy.CURRENT)
  18. public static MethodValidationPostProcessor methodValidationPostProcessor(Environment environment,
  19. @Lazy Validator validator, ObjectProvider<MethodValidationExcludeFilter> excludeFilters) {
  20. FilteredMethodValidationPostProcessor processor = new FilteredMethodValidationPostProcessor(
  21. excludeFilters.orderedStream());
  22. boolean proxyTargetClass = environment.getProperty("spring.aop.proxy-target-class", Boolean.class, true);
  23. processor.setProxyTargetClass(proxyTargetClass);
  24. processor.setValidator(validator);
  25. return processor;
  26. }
  27. }

�我们可以看到上面类中创建了默认的校验器bean defaultValidator,真正的装配的操作还是依赖于 LocalValidatorFactoryBean类自身所实现的Spring接口InitializingBean来实现的, 我们可以看afterPropertiesSet方法。

  1. public void afterPropertiesSet() {
  2. ......
  3. try {
  4. this.validatorFactory = configuration.buildValidatorFactory();
  5. // 获取hibernate-validator, 设置到targetValidator中
  6. setTargetValidator(this.validatorFactory.getValidator());
  7. }
  8. finally {
  9. closeMappingStreams(mappingStreams);
  10. }
  11. }

�WebMvcAutoConfiguration

�已经创建好默认的validator,我们要把这个默认的validator设置到web mvc中,所以我们把目光关注到WebMvcAutoConfiguration中。

  1. @Configuration(proxyBeanMethods = false)
  2. @EnableConfigurationProperties(WebProperties.class)
  3. public static class EnableWebMvcConfiguration extends DelegatingWebMvcConfiguration implements ResourceLoaderAware {
  4. // 创建validator bean, 其实用的就是hibernate-validator
  5. @Bean
  6. @Override
  7. public Validator mvcValidator() {
  8. if (!ClassUtils.isPresent("javax.validation.Validator", getClass().getClassLoader())) {
  9. return super.mvcValidator();
  10. }
  11. return ValidatorAdapter.get(getApplicationContext(), getValidator());
  12. }
  13. @Bean
  14. @Override
  15. public RequestMappingHandlerAdapter requestMappingHandlerAdapter(
  16. @Qualifier("mvcContentNegotiationManager") ContentNegotiationManager contentNegotiationManager,
  17. @Qualifier("mvcConversionService") FormattingConversionService conversionService,
  18. @Qualifier("mvcValidator") Validator validator) {
  19. // 将validator设置到RequestMappingHandlerAdapter中,正是它负责处理Controller层注解@RequestMapping 修饰的方法请求调用)
  20. RequestMappingHandlerAdapter adapter = super.requestMappingHandlerAdapter(contentNegotiationManager,
  21. conversionService, validator);
  22. adapter.setIgnoreDefaultModelOnRedirect(
  23. this.mvcProperties == null || this.mvcProperties.isIgnoreDefaultModelOnRedirect());
  24. return adapter;
  25. }
  26. }

参考

https://juejin.cn/post/7109131754182541348#heading-22
https://www.cnblogs.com/qdhxhz/p/15639059.html
https://blog.csdn.net/lqzkcx3/article/details/108035447