Spring Boot starter原理


Spring Boot starter原理

一、starter自動配置類導入

啟動類上@SpringBootApplication -> 引入AutoConfigurationImportSelector -> ConfigurationClassParser 中處理 -> 獲取spring.factories中EnableAutoConfiguration實現

 

1、進入AutoConfigurationImportSelector類的getAutoConfigurationEntry方法

 

 

2、然后進入getCandidateConfigurations類。

該方法作用是獲得spring.factories當中實現EnableAutoConfiguration接口的類

 

 

3 獲得所有實現了EnableAutoConfiguration的類

 

 

4、最終有WeacherAutoConfiguration

 

 

 

二、自動配置類的過濾

1、進入WeatherAutoConfiguration類

 

 2、進入ConditionalOnProperty注解

 

 

3、然后進入OnPropertyCondition類的getMatchOutcome方法。當metadata為com.exmaple.demo.WeatherAutoConfiguration時

遍歷注解里的屬性,增加到對應的math或者noMatch集合中。如果存在noMatch,則返回不匹配

 

 

4、進入determineOutcome方法

    private ConditionOutcome determineOutcome(AnnotationAttributes annotationAttributes, PropertyResolver resolver) {
        OnPropertyCondition.Spec spec = new OnPropertyCondition.Spec(annotationAttributes);
        List<String> missingProperties = new ArrayList();
        List<String> nonMatchingProperties = new ArrayList();
        spec.collectProperties(resolver, missingProperties, nonMatchingProperties);
        return !missingProperties.isEmpty()?ConditionOutcome.noMatch(ConditionMessage.forCondition(ConditionalOnProperty.class, new Object[]{spec}).didNotFind("property", "properties").items(Style.QUOTE, missingProperties)):(!nonMatchingProperties.isEmpty()?ConditionOutcome.noMatch(ConditionMessage.forCondition(ConditionalOnProperty.class, new Object[]{spec}).found("different value in property", "different value in properties").items(Style.QUOTE, nonMatchingProperties)):ConditionOutcome.match(ConditionMessage.forCondition(ConditionalOnProperty.class, new Object[]{spec}).because("matched")));
    }

  

5、進入collectProperties方法

比較屬性值是否匹配

        private void collectProperties(PropertyResolver resolver, List<String> missing, List<String> nonMatching) {
            String[] var4 = this.names;
            int var5 = var4.length;

            for(int var6 = 0; var6 < var5; ++var6) {
                String name = var4[var6];
                String key = this.prefix + name;
                if(resolver.containsProperty(key)) {
                    if(!this.isMatch(resolver.getProperty(key), this.havingValue)) {
                        nonMatching.add(name);
                    }
                } else if(!this.matchIfMissing) {
                    missing.add(name);
                }
            }

        }

  最終通過equal判斷是否匹配。

   private boolean isMatch(String value, String requiredValue) {
            return StringUtils.hasLength(requiredValue)?requiredValue.equalsIgnoreCase(value):!"false".equalsIgnoreCase(value);
        }

  


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM