日韩无码专区无码一级三级片|91人人爱网站中日韩无码电影|厨房大战丰满熟妇|AV高清无码在线免费观看|另类AV日韩少妇熟女|中文日本大黄一级黄色片|色情在线视频免费|亚洲成人特黄a片|黄片wwwav色图欧美|欧亚乱色一区二区三区

RELATEED CONSULTING
相關(guān)咨詢
選擇下列產(chǎn)品馬上在線溝通
服務(wù)時(shí)間:8:30-17:00
你可能遇到了下面的問題
關(guān)閉右側(cè)工具欄

新聞中心

這里有您想知道的互聯(lián)網(wǎng)營(yíng)銷解決方案
Spring創(chuàng)建Bean時(shí)是怎樣判斷條件的?

 我們?cè)?Spring/ Spring Boot Starter 或者一些框架的源碼里經(jīng)常能看到類似如下的注解聲明,可能作用在類上,也可能在某個(gè)方法上:

創(chuàng)新互聯(lián)建站專注于成縣企業(yè)網(wǎng)站建設(shè),成都響應(yīng)式網(wǎng)站建設(shè)公司,商城建設(shè)。成縣網(wǎng)站建設(shè)公司,為成縣等地區(qū)提供建站服務(wù)。全流程按需定制設(shè)計(jì),專業(yè)設(shè)計(jì),全程項(xiàng)目跟蹤,創(chuàng)新互聯(lián)建站專業(yè)和態(tài)度為您提供的服務(wù)

 
 
 
 
  1. @ConditionalOnProperty(name = "spring.cloud.refresh.enabled", matchIfMissing = true) 
  2.  
  3. @ConditionalOnProperty(prefix = "management.metrics.export.atlas", name = "enabled", havingValue = "true", 
  4.     matchIfMissing = true) 

我們一眼都能看出來,這是來「談條件」的。需要滿足某個(gè)屬性存在,或者屬性值是xx這一類的。

對(duì)于屬性的匹配,是會(huì)在 Environment 里查找是否包含當(dāng)前需要的屬性,如果沒指定 havingValue 的話,那需要同時(shí)屬性的值不為「false」這個(gè)字符串,其它的東西都視為true。

今天的這篇做為鋪墊,先來描述一下注解的工作原理,后面一篇我會(huì)寫寫與此有關(guān)的一個(gè)有趣的案例。

工作原理

濃縮版

在SpringBoot 啟動(dòng)過程中,會(huì)掃描當(dāng)前依賴?yán)锏?@Configuration,然后遍歷的過程中會(huì)判斷其中哪些是要講條件的。對(duì)于講條件的這些,會(huì)判斷

shouldSkip ,這里的是否跳過,會(huì)根據(jù)注解作用在類上,方法上,轉(zhuǎn)向不同的Metadata,提取對(duì)應(yīng)的實(shí)現(xiàn)類,但本質(zhì)上還是通過 resolver 去Environment 里找找這個(gè)屬性在不在,不在跳過,在的話是否值匹配。從而決定 Confirutaion 是否生效。

源碼版

我們知道 Spring 啟動(dòng)的過程,也是創(chuàng)建和初始化Bean 的過程,在這個(gè)過程中,會(huì)先拿到BeanNames,并一個(gè)個(gè)的去創(chuàng)建和初始化。

此時(shí),對(duì)于Configuration,是通過BeanPostProcessor的方式來處理的.

 
 
 
 
  1. public void postProcessBeanDefinitionRegistry(BeanDefinitionRegistry registry) { 
  2.     int registryId = System.identityHashCode(registry); 
  3.     this.registriesPostProcessed.add(registryId); 
  4.     processConfigBeanDefinitions(registry);// 對(duì),是這里 
  5.   } 

部分調(diào)用棧如下:

 
 
 
 
  1. java.lang.Thread.State: RUNNABLE 
  2.     at org.springframework.boot.autoconfigure.condition.OnPropertyCondition.getMatchOutcome(OnPropertyCondition.java:65) 
  3.     at org.springframework.boot.autoconfigure.condition.SpringBootCondition.matches(SpringBootCondition.java:47) 
  4.     at org.springframework.context.annotation.ConditionEvaluator.shouldSkip(ConditionEvaluator.java:108) 
  5.     at org.springframework.context.annotation.ConfigurationClassBeanDefinitionReader.loadBeanDefinitionsForBeanMethod(ConfigurationClassBeanDefinitionReader.java:181) 
  6.     at org.springframework.context.annotation.ConfigurationClassBeanDefinitionReader.loadBeanDefinitionsForConfigurationClass(ConfigurationClassBeanDefinitionReader.java:142) 
  7.     at org.springframework.context.annotation.ConfigurationClassBeanDefinitionReader.loadBeanDefinitions(ConfigurationClassBeanDefinitionReader.java:118) 
  8.     at org.springframework.context.annotation.ConfigurationClassPostProcessor.processConfigBeanDefinitions(ConfigurationClassPostProcessor.java:328) 
  9.     at org.springframework.context.annotation.ConfigurationClassPostProcessor.postProcessBeanDefinitionRegistry(ConfigurationClassPostProcessor.java:233) 

這里對(duì)于 Class 和 Method,都在該方法中,處理入口不一樣,傳入的Meta也有所區(qū)別

 
 
 
 
  1. /** 
  2.    * Build and validate a configuration model based on the registry of 
  3.    * {@link Configuration} classes. 
  4.    */ 
  5.   public void processConfigBeanDefinitions(BeanDefinitionRegistry registry) { 
  6.     List configCandidates = new ArrayList<>(); 
  7.     String[] candidateNames = registry.getBeanDefinitionNames(); 
  8.  
  9.     for (String beanName : candidateNames) { 
  10.       BeanDefinition beanDef = registry.getBeanDefinition(beanName); 
  11.       if (ConfigurationClassUtils.isFullConfigurationClass(beanDef) || 
  12.           ConfigurationClassUtils.isLiteConfigurationClass(beanDef)) { 
  13.       } 
  14.       else if (ConfigurationClassUtils.checkConfigurationClassCandidate(beanDef, this.metadataReaderFactory)) { 
  15.         configCandidates.add(new BeanDefinitionHolder(beanDef, beanName)); 
  16.       } 
  17.     } 
  18.     // Return immediately if no @Configuration classes were found 
  19.     if (configCandidates.isEmpty()) { 
  20.       return; 
  21.     } 
  22.  
  23.     // Parse each @Configuration class 
  24.     ConfigurationClassParser parser = new ConfigurationClassParser( 
  25.         this.metadataReaderFactory, this.problemReporter, this.environment, 
  26.         this.resourceLoader, this.componentScanBeanNameGenerator, registry); 
  27.  
  28.     Set candidates = new LinkedHashSet<>(configCandidates); 
  29.     Set alreadyParsed = new HashSet<>(configCandidates.size()); 
  30.     do { 
  31.       parser.parse(candidates); // 這里處理class 
  32.       parser.validate(); 
  33.  
  34.       Set configClasses = new LinkedHashSet<>(parser.getConfigurationClasses()); 
  35.       configClasses.removeAll(alreadyParsed); 
  36.  
  37.       // Read the model and create bean definitions based on its content 
  38.       if (this.reader == null) { 
  39.         this.reader = new ConfigurationClassBeanDefinitionReader( 
  40.             registry, this.sourceExtractor, this.resourceLoader, this.environment, 
  41.             this.importBeanNameGenerator, parser.getImportRegistry()); 
  42.       } 
  43.       this.reader.loadBeanDefinitions(configClasses); // 這里處理Method 
  44.       alreadyParsed.addAll(configClasses); 
  45.     while (!candidates.isEmpty()); 
  46.   } 

里面的邏輯,則都是在判斷這些Condition 是否match,重點(diǎn)看這一行

condition.matches(this.context, metadata)

 
 
 
 
  1. for (Condition condition : conditions) { 
  2.       ConfigurationPhase requiredPhase = null; 
  3.       if (condition instanceof ConfigurationCondition) { 
  4.         requiredPhase = ((ConfigurationCondition) condition).getConfigurationPhase(); 
  5.       } 
  6.       if ((requiredPhase == null || requiredPhase == phase) && !condition.matches(this.context, metadata)) { 
  7.         return true; 
  8.       } 
  9.     } 

通過觀察 Condition 這個(gè)接口你也能發(fā)現(xiàn),和我們上面說的一樣,這里不同的處理metadata是不同的。

在 SpringBoot 里,ConditionalOnProperty 的 Condition 實(shí)現(xiàn),運(yùn)用了一個(gè)模板方法模式, SpringBootCondition 做為模板,再調(diào)用各子類的實(shí)現(xiàn)方法。

 
 
 
 
  1. public final boolean matches(ConditionContext context, 
  2.       AnnotatedTypeMetadata metadata) { 
  3.     String classOrMethodName = getClassOrMethodName(metadata); 
  4.       ConditionOutcome outcome = getMatchOutcome(context, metadata);// 這里交給了抽象方法 
  5.       recordEvaluation(context, classOrMethodName, outcome); 
  6.       return outcome.isMatch(); 
  7.   } 

來看子類的實(shí)現(xiàn)

 
 
 
 
  1. private ConditionOutcome determineOutcome(AnnotationAttributes annotationAttributes, 
  2.       PropertyResolver resolver) { 
  3.     Spec spec = new Spec(annotationAttributes); 
  4.     List missingProperties = new ArrayList<>(); 
  5.     List nonMatchingProperties = new ArrayList<>(); 
  6.     spec.collectProperties(resolver, missingProperties, nonMatchingProperties); 
  7.     if (!missingProperties.isEmpty()) { 
  8.       return ConditionOutcome.noMatch( 
  9.           ConditionMessage.forCondition(ConditionalOnProperty.class, spec) 
  10.               .didNotFind("property", "properties") 
  11.               .items(Style.QUOTE, missingProperties)); 
  12.     } 
  13.     if (!nonMatchingProperties.isEmpty()) { 
  14.       return ConditionOutcome.noMatch( 
  15.           ConditionMessage.forCondition(ConditionalOnProperty.class, spec) 
  16.               .found("different value in property", 
  17.                   "different value in properties") 
  18.               .items(Style.QUOTE, nonMatchingProperties)); 
  19.     } 
  20.     return ConditionOutcome.match(ConditionMessage 
  21.         .forCondition(ConditionalOnProperty.class, spec).because("matched")); 
  22.   } 

有了這個(gè)判斷,對(duì)于 OnClass 之類的,你也能猜個(gè)八九不離十。

同樣會(huì)有一個(gè)子類的實(shí)現(xiàn)

只不過判斷的從屬性,換成了在classloader里查找已加載的類。

本文轉(zhuǎn)載自微信公眾號(hào)「Tomcat那些事兒」,可以通過以下二維碼關(guān)注。轉(zhuǎn)載本文請(qǐng)聯(lián)系Tomcat那些事兒公眾號(hào)。


網(wǎng)站欄目:Spring創(chuàng)建Bean時(shí)是怎樣判斷條件的?
文章起源:http://www.5511xx.com/article/dpeohic.html