最近要作動態數據的提交處理,即須要分析提交數據字段定義信息後才能明確對應的具體字段類型,進而作數據類型轉換和字段有效性校驗,而後作業務處理後提交數據庫,本身開發一套校驗邏輯的話週期太長,所以分析了Spring Validation的實現原理,複用了其底層花樣繁多的Validator,在此將分析Spring Validation原理的過程記錄下,不深刻細節spring
@Bean public BeanPostProcessor beanValidationPostProcessor() { return new BeanValidationPostProcessor(); } @Bean public UserModel getUserModel() { UserModel userModel = new UserModel(); userModel.setUsername(null); userModel.setPassword("123"); return userModel; } @Data class UserModel { @NotNull(message = "username can not be null") @Pattern(regexp = "[a-zA-Z0-9_]{5,10}", message = "username is illegal") private String username; @Size(min = 5, max = 10, message = "password's length is illegal") private String password; } 複製代碼
四、BeanValidationPostProcessor Bean內部有個boolean類型的屬性afterInitialization,默認是false,若是是false,在postProcessBeforeInitialization過程當中對bean進行驗證,不然在postProcessAfterInitialization過程對bean進行驗證
五、此種校驗使用了spring的BeanPostProcessor邏輯,可參考Spring Boot系列之一:如何快速熟悉Spring技術棧
六、校驗底層調用了doValidate方法,進一步調用validator.validate,默認validator爲HibernateValidator,validation-api包爲JAVA規範,Spring默認的規範實現爲hibernate-validator包,此hibernate非ORM框架Hibernate數據庫
protected void doValidate(Object bean) { Assert.state(this.validator != null, "No Validator set"); Set<ConstraintViolation<Object>> result = this.validator.validate(bean); 複製代碼
七、HibernateValidator默認調用ValidatorFactoryImpl來生成validator,後面展開將ValidatorFactoryImplapi
@Component @Validated public class BeanForMethodValidation { public void validate(@NotEmpty String name, @Min(10) int age) { System.out.println("validate, name: " + name + ", age: " + age); } } 複製代碼
四、MethodValidationPostProcessor內部使用aop完成對方法的調用bash
public void afterPropertiesSet() { Pointcut pointcut = new `AnnotationMatchingPointcut`(this.validatedAnnotationType, true); this.advisor = new `DefaultPointcutAdvisor`(pointcut, createMethodValidationAdvice(this.validator)); } protected Advice createMethodValidationAdvice(@Nullable Validator validator) { return (validator != null ? new `MethodValidationInterceptor`(validator) : new MethodValidationInterceptor()); } 複製代碼
五、底層一樣默認調用ValidatorFactoryImpl來生成validator,由validator完成校驗微信
public class Person { @NotNull(message = "性別不能爲空") private Gender gender; @Min(10) private Integer age; ... } ValidatorFactory validatorFactory = Validation.buildDefaultValidatorFactory(); Validator validator = validatorFactory.getValidator(); Person person = new Person(); person.setGender(Gender.Man); validator.validate(person); 複製代碼
同上,默認調用ValidatorFactoryImpl來生成validator,由validator完成具體校驗markdown
valid或validated
註解標註待校驗參數public Validator `getValidator`() { return `createValidator`( constraintValidatorManager.getDefaultConstraintValidatorFactory(), valueExtractorManager, validatorFactoryScopedContext, methodValidationConfiguration ); } Validator `createValidator`(ConstraintValidatorFactory constraintValidatorFactory, ValueExtractorManager valueExtractorManager, ValidatorFactoryScopedContext validatorFactoryScopedContext, MethodValidationConfiguration methodValidationConfiguration) { BeanMetaDataManager beanMetaDataManager = beanMetaDataManagers.computeIfAbsent( new BeanMetaDataManagerKey( validatorFactoryScopedContext.getParameterNameProvider(), valueExtractorManager, methodValidationConfiguration ), key -> new BeanMetaDataManager( `constraintHelper`, executableHelper, typeResolutionHelper, validatorFactoryScopedContext.getParameterNameProvider(), valueExtractorManager, validationOrderGenerator, buildDataProviders(), methodValidationConfiguration ) ); return `new ValidatorImpl`( constraintValidatorFactory, beanMetaDataManager, valueExtractorManager, constraintValidatorManager, validationOrderGenerator, validatorFactoryScopedContext ); } public final <T> Set<ConstraintViolation<T>> validate(T object, Class<?>... groups) { Contracts.assertNotNull( object, MESSAGES.validatedObjectMustNotBeNull() ); sanityCheckGroups( groups ); ValidationContext<T> validationContext = `getValidationContextBuilder().forValidate( object )`; if ( !validationContext.getRootBeanMetaData().hasConstraints() ) { return Collections.emptySet(); } ValidationOrder validationOrder = determineGroupValidationOrder( groups ); ValueContext<?, Object> valueContext = `ValueContext.getLocalExecutionContext`( validatorScopedContext.getParameterNameProvider(), object, validationContext.getRootBeanMetaData(), PathImpl.createRootPath() ); return validateInContext( validationContext, valueContext, validationOrder ); } 複製代碼
一、getValidator->createValidator->ValidatorImpl->validate
在執行過程當中封裝了beanMetaDataManager、validationContext、valueContext等內容,都是校驗時會用到的上下文信息,如待校驗bean的全部校驗項(含父類和接口)、property、method parameter的校驗信息,從ValidatorFactoryScopedContext繼承過來的validator通用的各類工具類(如message、script等的處理)等,內容比較複雜
二、分組(group)校驗忽略,來到默認分組處理validateConstraintsForDefaultGroup->validateConstraintsForSingleDefaultGroupElement->validateMetaConstraint(注:metaConstraints維護了該bean類型及其父類、接口的全部校驗,須要遍歷調用validateMetaConstraint)
三、繼續調用MetaConstraint的doValidateConstraint方法,根據不一樣的annotation type走不一樣的ConstraintTree框架
public static <U extends Annotation> ConstraintTree<U> of(ConstraintDescriptorImpl<U> composingDescriptor, Type validatedValueType) { if ( composingDescriptor.getComposingConstraintImpls().isEmpty() ) { return new SimpleConstraintTree<>( composingDescriptor, validatedValueType ); } else { return new ComposingConstraintTree<>( composingDescriptor, validatedValueType ); } } 複製代碼
四、具體哪些走simple,哪些走composing暫且無論,由於兩者都調用了ConstraintTree的'getInitializedConstraintValidator'方法,該步用來獲取校驗annotation(如DecimalMax、NotEmpty等)對應的validator並初始化validator 五、ConstraintHelper
類維護了全部builtin的validator,並根據校驗annotation(如DecimalMax)分類,validator的描述類中維護了該validator的泛型模板(如BigDecimal),以下:ide
putConstraints( tmpConstraints, DecimalMax.class, Arrays.asList(
DecimalMaxValidatorForBigDecimal.class,
DecimalMaxValidatorForBigInteger.class,
DecimalMaxValidatorForDouble.class,
DecimalMaxValidatorForFloat.class,
DecimalMaxValidatorForLong.class,
DecimalMaxValidatorForNumber.class,
DecimalMaxValidatorForCharSequence.class,
DecimalMaxValidatorForMonetaryAmount.class
) );
複製代碼
在獲取具體bean類的validator時,先根據annotation獲取全部的validator,對應方法是ConstraintManager.findMatchingValidatorDescriptor,而後根據被校驗對象的類型獲取惟一的validator
六、而後根據上下文信息initializeValidator,進而調用validator的isValid方法校驗工具