Spring Validation方法实现原理分析
最近要做动态数据的提交处理,即需要分析提交数据字段定义信息后才能明确对应的具体字段类型,进而做数据类型转换和字段有效性校验,然后做业务处理后提交数据库,自己开发一套校验逻辑的话周期太长,因此分析了spring validation的实现原理,复用了其底层花样繁多的validator,在此将分析spring validation原理的过程记录下,不深入细节
如何使用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<constraintviolation<object>> 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 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 ); }
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 <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 ); } }
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方法校验
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。