源码解析
执行流程
这是一个springmvc的应用,请求进来,通过DispatcherServlet
类转发,最终调到RequestResponseBodyMethodProcessor
类的resolveArgument()
方法。
首先查看RequestResponseBodyMethodProcessor
的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(); // 将请求数据转换到对象中 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); } }
关键方法validateIfApplicable()
中进行数据校验。
protected void validateIfApplicable(WebDataBinder binder, MethodParameter parameter) { // 获取参数上绑定的注解,如@Valid, @Validated等 Annotation[] annotations = parameter.getParameterAnnotations(); // 遍历注解 for (Annotation ann : annotations) { // 关键方法,判断是否进行数据校验 Object[] validationHints = ValidationAnnotationUtils.determineValidationHints(ann); // 如果数据校验注解不为空,开启后续的校验流程 if (validationHints != null) { binder.validate(validationHints); break; } } }
看下ValidationAnnotationUtils.determineValidationHints()
@Nullable public static Object[] determineValidationHints(Annotation ann) { Class<? extends Annotation> annotationType = ann.annotationType(); String annotationName = annotationType.getName(); // 判断注解名称是否为Valid if ("javax.validation.Valid".equals(annotationName)) { return EMPTY_OBJECT_ARRAY; } // 判断注解是否是Validated Validated validatedAnn = AnnotationUtils.getAnnotation(ann, Validated.class); if (validatedAnn != null) { Object hints = validatedAnn.value(); return convertValidationHints(hints); } // 判断注解是否是以Valid开头 if (annotationType.getSimpleName().startsWith("Valid")) { Object hints = AnnotationUtils.getValue(ann); return convertValidationHints(hints); } // 返回空,表示不需要进行校验 return null; }
所以看到,最终程序兼容了@Valid
和@Validated
注解,他们都会开启参数校验。接着就要开启校验流程了,最终方法走到了SpringValidatorAdapter#validate()
。
@Override public void validate(Object target, Errors errors) { if (this.targetValidator != null) { // 调用数据校验工作,这里的targetValidator是hibernate-validator中ValidatorImpl类 processConstraintViolations(this.targetValidator.validate(target), errors); } }
走到了ValidatorImpl#validate
方法
// 该方法主要用于开启校验的一些准备巩固走 @Override public final <T> Set<ConstraintViolation<T>> validate(T object, Class<?>... groups) { Contracts.assertNotNull( object, MESSAGES.validatedObjectMustNotBeNull() ); sanityCheckGroups( groups ); @SuppressWarnings("unchecked") Class<T> rootBeanClass = (Class<T>) object.getClass(); BeanMetaData<T> rootBeanMetaData = beanMetaDataManager.getBeanMetaData( rootBeanClass ); if ( !rootBeanMetaData.hasConstraints() ) { return Collections.emptySet(); } // 获取验证的上下文,主要就是获取@NotNull, @Max等校验数据 BaseBeanValidationContext<T> validationContext = getValidationContextBuilder().forValidate( rootBeanClass, rootBeanMetaData, object ); ValidationOrder validationOrder = determineGroupValidationOrder( groups ); // 创建请求参数数据上下文 BeanValueContext<?, Object> valueContext = ValueContexts.getLocalExecutionContextForBean( validatorScopedContext.getParameterNameProvider(), object, validationContext.getRootBeanMetaData(), PathImpl.createRootPath() ); // 开始校验 return validateInContext( validationContext, valueContext, validationOrder ); } // 该方法是使用校验的上下文信息进行数据校验工作 private <T, U> Set<ConstraintViolation<T>> validateInContext(BaseBeanValidationContext<T> validationContext, BeanValueContext<U, Object> valueContext, ValidationOrder validationOrder) { if ( valueContext.getCurrentBean() == null ) { return Collections.emptySet(); } BeanMetaData<U> beanMetaData = valueContext.getCurrentBeanMetaData(); if ( beanMetaData.isDefaultGroupSequenceRedefined() ) { validationOrder.assertDefaultGroupSequenceIsExpandable( beanMetaData.getDefaultGroupSequence( valueContext.getCurrentBean() ) ); } // 处理单个组的校验,也就是最简单的那种校验逻辑 Iterator<Group> groupIterator = validationOrder.getGroupIterator(); while ( groupIterator.hasNext() ) { Group group = groupIterator.next(); valueContext.setCurrentGroup( group.getDefiningClass() ); validateConstraintsForCurrentGroup( validationContext, valueContext ); if ( shouldFailFast( validationContext ) ) { return validationContext.getFailingConstraints(); } } // 执行有级联约束的校验 groupIterator = validationOrder.getGroupIterator(); while ( groupIterator.hasNext() ) { Group group = groupIterator.next(); valueContext.setCurrentGroup( group.getDefiningClass() ); validateCascadedConstraints( validationContext, valueContext ); if ( shouldFailFast( validationContext ) ) { return validationContext.getFailingConstraints(); } } Iterator<Sequence> sequenceIterator = validationOrder.getSequenceIterator(); while ( sequenceIterator.hasNext() ) { Sequence sequence = sequenceIterator.next(); for ( GroupWithInheritance groupOfGroups : sequence ) { int numberOfViolations = validationContext.getFailingConstraints().size(); for ( Group group : groupOfGroups ) { valueContext.setCurrentGroup( group.getDefiningClass() ); validateConstraintsForCurrentGroup( validationContext, valueContext ); if ( shouldFailFast( validationContext ) ) { return validationContext.getFailingConstraints(); } validateCascadedConstraints( validationContext, valueContext ); if ( shouldFailFast( validationContext ) ) { return validationContext.getFailingConstraints(); } } if ( validationContext.getFailingConstraints().size() > numberOfViolations ) { break; } } } return validationContext.getFailingConstraints(); }
我们关注在普通的数据校验处理validateConstraintsForCurrentGroup()
方法。
private void validateConstraintsForCurrentGroup(BaseBeanValidationContext<?> validationContext, BeanValueContext<?, Object> valueContext) { // we are not validating the default group there is nothing special to consider. If we are validating the default // group sequence we have to consider that a class in the hierarchy could redefine the default group sequence. // 如果不是默认分组的情况 if ( !valueContext.validatingDefault() ) { validateConstraintsForNonDefaultGroup( validationContext, valueContext ); } // 如果是默认分组的情况 else { validateConstraintsForDefaultGroup( validationContext, valueContext ); } } private <U> void validateConstraintsForDefaultGroup(BaseBeanValidationContext<?> validationContext, BeanValueContext<U, Object> valueContext) { final BeanMetaData<U> beanMetaData = valueContext.getCurrentBeanMetaData(); final Map<Class<?>, Class<?>> validatedInterfaces = new HashMap<>(); // evaluating the constraints of a bean per class in hierarchy, this is necessary to detect potential default group re-definitions for ( Class<? super U> clazz : beanMetaData.getClassHierarchy() ) { BeanMetaData<? super U> hostingBeanMetaData = beanMetaDataManager.getBeanMetaData( clazz ); boolean defaultGroupSequenceIsRedefined = hostingBeanMetaData.isDefaultGroupSequenceRedefined(); // if the current class redefined the default group sequence, this sequence has to be applied to all the class hierarchy. if ( defaultGroupSequenceIsRedefined ) { Iterator<Sequence> defaultGroupSequence = hostingBeanMetaData.getDefaultValidationSequence( valueContext.getCurrentBean() ); Set<MetaConstraint<?>> metaConstraints = hostingBeanMetaData.getMetaConstraints(); while ( defaultGroupSequence.hasNext() ) { for ( GroupWithInheritance groupOfGroups : defaultGroupSequence.next() ) { boolean validationSuccessful = true; for ( Group defaultSequenceMember : groupOfGroups ) { validationSuccessful = validateConstraintsForSingleDefaultGroupElement( validationContext, valueContext, validatedInterfaces, clazz, metaConstraints, defaultSequenceMember ) && validationSuccessful; } validationContext.markCurrentBeanAsProcessed( valueContext ); if ( !validationSuccessful ) { break; } } } } // fast path in case the default group sequence hasn't been redefined else { Set<MetaConstraint<?>> metaConstraints = hostingBeanMetaData.getDirectMetaConstraints(); // 执行校验操作 validateConstraintsForSingleDefaultGroupElement( validationContext, valueContext, validatedInterfaces, clazz, metaConstraints, Group.DEFAULT_GROUP ); validationContext.markCurrentBeanAsProcessed( valueContext ); } // all constraints in the hierarchy has been validated, stop validation. if ( defaultGroupSequenceIsRedefined ) { break; } } }
最关键的方法是在validateConstraintsForSingleDefaultGroupElement()
方法中执行最终的数据校验,大家通过断点一步一步下去,最终发现走到了SimpleConstraintTree#validateConstraints()
@Override protected void validateConstraints(ValidationContext<?> validationContext, ValueContext<?, ?> valueContext, Collection<ConstraintValidatorContextImpl> violatedConstraintValidatorContexts) { if ( LOG.isTraceEnabled() ) { LOG.tracef( "Validating value %s against constraint defined by %s.", valueContext.getCurrentValidatedValue(), descriptor ); } // find the right constraint validator ConstraintValidator<B, ?> validator = getInitializedConstraintValidator( validationContext, valueContext ); // create a constraint validator context ConstraintValidatorContextImpl constraintValidatorContext = validationContext.createConstraintValidatorContextFor( descriptor, valueContext.getPropertyPath() ); // validate, 进行单个校验 if ( validateSingleConstraint( valueContext, constraintValidatorContext, validator ).isPresent() ) { violatedConstraintValidatorContexts.add( constraintValidatorContext ); } } protected final <V> Optional<ConstraintValidatorContextImpl> validateSingleConstraint( ValueContext<?, ?> valueContext, ConstraintValidatorContextImpl constraintValidatorContext, ConstraintValidator<A, V> validator) { boolean isValid; try { @SuppressWarnings("unchecked") V validatedValue = (V) valueContext.getCurrentValidatedValue(); // 执行各个校验器的校验方法,validator是一个接口,有很多具体校验的实现方法 isValid = validator.isValid( validatedValue, constraintValidatorContext ); } catch (RuntimeException e) { if ( e instanceof ConstraintDeclarationException ) { throw e; } throw LOG.getExceptionDuringIsValidCallException( e ); } if ( !isValid ) { //We do not add these violations yet, since we don't know how they are //going to influence the final boolean evaluation return Optional.of( constraintValidatorContext ); } return Optional.empty(); }
上面就是整个请求参数的校验流程。
初始化设置hibernate-validator
大家有没有想过请求数据的校验,为什么会选择hibernate-validator作为校验器,它又是在什么时候设置呢?我们从源码的角度看看。
ValidationAutoConfiguration
因为我们引入了spring-boot-starter-validation
,开启了自动装配,可以看到有个ValidationAutoConfiguration
类。
@AutoConfiguration @ConditionalOnClass(ExecutableValidator.class) @ConditionalOnResource(resources = "classpath:META-INF/services/javax.validation.spi.ValidationProvider") @Import(PrimaryDefaultValidatorPostProcessor.class) public class ValidationAutoConfiguration { // 创建默认的defaultValidator @Bean @Role(BeanDefinition.ROLE_INFRASTRUCTURE) @ConditionalOnMissingBean(Validator.class) public static LocalValidatorFactoryBean defaultValidator(ApplicationContext applicationContext) { LocalValidatorFactoryBean factoryBean = new LocalValidatorFactoryBean(); MessageInterpolatorFactory interpolatorFactory = new MessageInterpolatorFactory(applicationContext); factoryBean.setMessageInterpolator(interpolatorFactory.getObject()); return factoryBean; } @Bean @ConditionalOnMissingBean(search = SearchStrategy.CURRENT) public static MethodValidationPostProcessor methodValidationPostProcessor(Environment environment, @Lazy Validator validator, ObjectProvider<MethodValidationExcludeFilter> excludeFilters) { FilteredMethodValidationPostProcessor processor = new FilteredMethodValidationPostProcessor( excludeFilters.orderedStream()); boolean proxyTargetClass = environment.getProperty("spring.aop.proxy-target-class", Boolean.class, true); processor.setProxyTargetClass(proxyTargetClass); processor.setValidator(validator); return processor; } }
我们可以看到上面类中创建了默认的校验器bean defaultValidator
,真正的装配的操作还是依赖于 LocalValidatorFactoryBean
类自身所实现的Spring接口InitializingBean
来实现的, 我们可以看afterPropertiesSet
方法。
public void afterPropertiesSet() { ...... try { this.validatorFactory = configuration.buildValidatorFactory(); // 获取hibernate-validator, 设置到targetValidator中 setTargetValidator(this.validatorFactory.getValidator()); } finally { closeMappingStreams(mappingStreams); } }
WebMvcAutoConfiguration
已经创建好默认的validator,我们要把这个默认的validator设置到web mvc中,所以我们把目光关注到WebMvcAutoConfiguration
中。
@Configuration(proxyBeanMethods = false) @EnableConfigurationProperties(WebProperties.class) public static class EnableWebMvcConfiguration extends DelegatingWebMvcConfiguration implements ResourceLoaderAware { // 创建validator bean, 其实用的就是hibernate-validator @Bean @Override public Validator mvcValidator() { if (!ClassUtils.isPresent("javax.validation.Validator", getClass().getClassLoader())) { return super.mvcValidator(); } return ValidatorAdapter.get(getApplicationContext(), getValidator()); } @Bean @Override public RequestMappingHandlerAdapter requestMappingHandlerAdapter( @Qualifier("mvcContentNegotiationManager") ContentNegotiationManager contentNegotiationManager, @Qualifier("mvcConversionService") FormattingConversionService conversionService, @Qualifier("mvcValidator") Validator validator) { // 将validator设置到RequestMappingHandlerAdapter中,正是它负责处理Controller层注解@RequestMapping 修饰的方法请求调用) RequestMappingHandlerAdapter adapter = super.requestMappingHandlerAdapter(contentNegotiationManager, conversionService, validator); adapter.setIgnoreDefaultModelOnRedirect( this.mvcProperties == null || this.mvcProperties.isIgnoreDefaultModelOnRedirect()); return adapter; } }