欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

Spring Validation方法實現(xiàn)原理分析

 更新時間:2018年07月10日 08:39:43   作者:68號小喇叭  
這篇文章主要介紹了Spring Validation實現(xiàn)原理分析,小編覺得挺不錯的,現(xiàn)在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧

最近要做動態(tài)數(shù)據(jù)的提交處理,即需要分析提交數(shù)據(jù)字段定義信息后才能明確對應的具體字段類型,進而做數(shù)據(jù)類型轉換和字段有效性校驗,然后做業(yè)務處理后提交數(shù)據(jù)庫,自己開發(fā)一套校驗邏輯的話周期太長,因此分析了Spring Validation的實現(xiàn)原理,復用了其底層花樣繁多的Validator,在此將分析Spring Validation原理的過程記錄下,不深入細節(jié)

如何使用Spring Validation

Spring Bean初始化時校驗Bean是否符合JSR-303規(guī)范

1、手動添加BeanValidationPostProcessor Bean

2、在model類中定義校驗規(guī)則,如@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規(guī)范,Spring默認的規(guī)范實現(xiàn)為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規(guī)范

1、手動添加MethodValidationPostProcessor Bean

2、類上加上@Validated注解(也支持自定義注解,創(chuàng)建MethodValidationPostProcessor Bean時傳入)

3、在方法的參數(shù)中加上驗證注解,比如@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方法參數(shù)中使用valid或validated注解標注待校驗參數(shù)

1、先熟悉下Spring的請求調用流程

2、可以看到在各種resolver處理請求參數(shù)的過程中做了參數(shù)校驗

3、底層統(tǒng)一調用了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提交的字符串形式的參數(shù),將其轉換成服務端真正需要的類型,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

在執(zhí)行過程中封裝了beanMetaDataManager、validationContext、valueContext等內容,都是校驗時會用到的上下文信息,如待校驗bean的所有校驗項(含父類和接口)、property、method parameter的校驗信息,從ValidatorFactoryScopedContext繼承過來的validator通用的各種工具類(如message、script等的處理)等,內容比較復雜

2、分組(group)校驗忽略,來到默認分組處理validateConstraintsForDefaultGroup->validateConstraintsForSingleDefaultGroupElement->validateMetaConstraint(注:metaConstraints維護了該bean類型及其父類、接口的所有校驗,需要遍歷調用validateMetaConstraint)

3、繼續(xù)調用MetaConstraint的doValidateConstraint方法,根據(jù)不同的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,并根據(jù)校驗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時,先根據(jù)annotation獲取所有的validator,對應方法是ConstraintManager.findMatchingValidatorDescriptor,然后根據(jù)被校驗對象的類型獲取唯一的validator

6、然后根據(jù)上下文信息initializeValidator,進而調用validator的isValid方法校驗

以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持腳本之家。

相關文章

  • IDEA中Web項目控制臺亂碼的問題及解決方法

    IDEA中Web項目控制臺亂碼的問題及解決方法

    這篇文章主要介紹了IDEA中Web項目控制臺亂碼的問題及解決方法,本文給大家介紹的非常詳細,對大家的學習或工作具有一定的參考借鑒價值,需要的朋友可以參考下
    2020-08-08
  • Mybatis-Plus分頁的使用與注意事項

    Mybatis-Plus分頁的使用與注意事項

    分頁查詢每個人程序猿幾乎都使用過,下面這篇文章主要給大家介紹了關于Mybatis-Plus分頁的使用與注意事項的相關資料,文中通過實例代碼介紹的非常詳細,需要的朋友可以參考下
    2022-04-04
  • JVM雙親委派模型知識詳細總結

    JVM雙親委派模型知識詳細總結

    今天帶各位小伙伴學習Java虛擬機的相關知識,文中對JVM雙親委派模型作了非常詳細的介紹,對正在學習java的小伙伴們有很好的幫助,需要的朋友可以參考下
    2021-05-05
  • Idea配置熱部署的詳細教程

    Idea配置熱部署的詳細教程

    這篇文章主要介紹了Idea配置熱部署的詳細教程,本文通過圖文并茂的形式給大家介紹的非常詳細,對大家的學習或工作具有一定的參考借鑒價值,需要的朋友可以參考下
    2020-07-07
  • 通過案例了解靜態(tài)修飾符static使用場景

    通過案例了解靜態(tài)修飾符static使用場景

    這篇文章主要介紹了通過案例了解靜態(tài)修飾符static使用場景,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友可以參考下
    2020-10-10
  • Java 網絡爬蟲基礎知識入門解析

    Java 網絡爬蟲基礎知識入門解析

    這篇文章主要介紹了Java 網絡爬蟲基礎知識入門解析,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友可以參考下
    2019-10-10
  • Maven添加reactor依賴失敗的解決方案

    Maven添加reactor依賴失敗的解決方案

    起初是自己在學spring boot3,結果到了reactor這一部分的時候,在項目的pom.xml文件中添加下列依賴報錯,接下來通過本文給大家介紹Maven添加reactor依賴失敗的解決方案,需要的朋友可以參考下
    2024-06-06
  • Java中用爬蟲進行解析的實例方法

    Java中用爬蟲進行解析的實例方法

    在本篇文章里小編給大家整理的是一篇關于Java中用爬蟲進行解析的實例方法,有需要的朋友們可以學習參考下。
    2020-12-12
  • Java Web項目中Spring框架處理JSON格式數(shù)據(jù)的方法

    Java Web項目中Spring框架處理JSON格式數(shù)據(jù)的方法

    Spring MVC是個靈活的框架,返回JSON數(shù)據(jù)的也有很多五花八門的方式,這里我們來整理一個最簡單的Java Web項目中Spring框架處理JSON格式數(shù)據(jù)的方法:
    2016-05-05
  • Java中如何將json字符串轉換成map/list

    Java中如何將json字符串轉換成map/list

    這篇文章主要介紹了Java中如何將json字符串轉換成map/list,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教
    2022-07-07

最新評論