91超碰碰碰碰久久久久久综合_超碰av人澡人澡人澡人澡人掠_国产黄大片在线观看画质优化_txt小说免费全本

溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務條款》

Spring Validation方法實現原理分析

發布時間:2020-10-14 17:01:30 來源:腳本之家 閱讀:309 作者:68號小喇叭 欄目:編程語言

最近要做動態數據的提交處理,即需要分析提交數據字段定義信息后才能明確對應的具體字段類型,進而做數據類型轉換和字段有效性校驗,然后做業務處理后提交數據庫,自己開發一套校驗邏輯的話周期太長,因此分析了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的請求調用流程

Spring Validation方法實現原理分析

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方法校驗

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

向AI問一下細節

免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。

AI

河南省| 蒙阴县| 沾化县| 玉田县| 绥德县| 陆河县| 潮安县| 南陵县| 乾安县| 桐庐县| 鄯善县| 攀枝花市| 玉门市| 汕尾市| 且末县| 榕江县| 明水县| 尖扎县| 横峰县| 河间市| 阳山县| 凤庆县| 黑龙江省| 武冈市| 庆城县| 紫云| 平陆县| 大冶市| 蒙阴县| 孝昌县| 广饶县| 沁阳市| 寿光市| 汕尾市| 尤溪县| 黎川县| 河北省| 伽师县| 万宁市| 多伦县| 乡城县|