重庆分公司,新征程启航
为企业提供网站建设、域名注册、服务器等服务
最近要做动态数据的提交处理,即需要分析提交数据字段定义信息后才能明确对应的具体字段类型,进而做数据类型转换和字段有效性校验,然后做业务处理后提交数据库,自己开发一套校验逻辑的话周期太长,因此分析了Spring Validation的实现原理,复用了其底层花样繁多的Validator,在此将分析Spring Validation原理的过程记录下,不深入细节
创新互联建站主营习水网站建设的网络公司,主营网站建设方案,成都App定制开发,习水h5小程序设计搭建,习水网站营销推广欢迎习水等地区企业咨询
如何使用Spring Validation
Spring Bean初始化时校验Bean是否符合JSR-303规范
1、手动添加BeanValidationPostProcessor Bean
2、在model类中定义校验规则,如@Max、@Min、@NotEmpty
3、声明Bean,综合代码如下:
@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; }
4、BeanValidationPostProcessor Bean内部有个boolean类型的属性afterInitialization,默认是false,如果是false,在postProcessBeforeInitialization过程中对bean进行验证,否则在postProcessAfterInitialization过程对bean进行验证
5、此种校验使用了spring的BeanPostProcessor逻辑
6、校验底层调用了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> result = this.validator.validate(bean);
7、HibernateValidator默认调用ValidatorFactoryImpl来生成validator,后面展开将ValidatorFactoryImpl
支持方法级别的JSR-303规范
1、手动添加MethodValidationPostProcessor Bean
2、类上加上@Validated注解(也支持自定义注解,创建MethodValidationPostProcessor Bean时传入)
3、在方法的参数中加上验证注解,比如@Max、@Min、@NotEmpty、@NotNull等,如
@Component @Validated public class BeanForMethodValidation { public void validate(@NotEmpty String name, @Min(10) int age) { System.out.println("validate, name: " + name + ", age: " + age); } }
4、MethodValidationPostProcessor内部使用aop完成对方法的调用
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()); }
5、底层同样默认调用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完成具体校验
在Spring controller方法参数中使用valid或validated注解标注待校验参数
1、先熟悉下Spring的请求调用流程
2、可以看到在各种resolver处理请求参数的过程中做了参数校验
3、底层统一调用了DataBinder的validate方法
4、DataBinder的作用:Binder that allows for setting property values onto a target object, including support for validation and binding result analysis,也就是binder处理了request提交的字符串形式的参数,将其转换成服务端真正需要的类型,binder提供了对validation的支持,可以存放校验结果
5、DataBinder的validator默认在ConfigurableWebBindingInitializer中初始化,默认使用OptionalValidatorFactoryBean,该Bean继承了LocalValidatorFactoryBean,LocalValidatorFactoryBean组合了ValidatorFactory、自定义校验属性等各种校验会用到的信息,默认使用ValidatorFactoryImpl来获取validator
至此,所有的线索都指向了ValidatorFactoryImpl,下面分析下该类
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 finalSet > validate(T object, Class<?>... groups) { Contracts.assertNotNull( object, MESSAGES.validatedObjectMustNotBeNull() ); sanityCheckGroups( groups ); ValidationContext 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 ); }
1、getValidator->createValidator->ValidatorImpl->validate
在执行过程中封装了beanMetaDataManager、validationContext、valueContext等内容,都是校验时会用到的上下文信息,如待校验bean的所有校验项(含父类和接口)、property、method parameter的校验信息,从ValidatorFactoryScopedContext继承过来的validator通用的各种工具类(如message、script等的处理)等,内容比较复杂
2、分组(group)校验忽略,来到默认分组处理validateConstraintsForDefaultGroup->validateConstraintsForSingleDefaultGroupElement->validateMetaConstraint(注:metaConstraints维护了该bean类型及其父类、接口的所有校验,需要遍历调用validateMetaConstraint)
3、继续调用MetaConstraint的doValidateConstraint方法,根据不同的annotation type走不同的ConstraintTree
public static ConstraintTree of(ConstraintDescriptorImpl composingDescriptor, Type validatedValueType) { if ( composingDescriptor.getComposingConstraintImpls().isEmpty() ) { return new SimpleConstraintTree<>( composingDescriptor, validatedValueType ); } else { return new ComposingConstraintTree<>( composingDescriptor, validatedValueType ); } }
4、具体哪些走simple,哪些走composing暂且不管,因为二者都调用了ConstraintTree的'getInitializedConstraintValidator'方法,该步用来获取校验annotation(如DecimalMax、NotEmpty等)对应的validator并初始化validator
5、 ConstraintHelper
类维护了所有builtin的validator,并根据校验annotation(如DecimalMax)分类,validator的描述类中维护了该validator的泛型模板(如BigDecimal),如下:
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
6、然后根据上下文信息initializeValidator,进而调用validator的isValid方法校验
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持创新互联。