美文网首页
Spring 条件装配 Condition 分析

Spring 条件装配 Condition 分析

作者: Tinyspot | 来源:发表于2023-12-21 11:43 被阅读0次

    1. 条件装配 Condition

    三个过滤器:OnClassCondition, OnBeanCondition, OnWebApplicationCondition

    顶层接口Condition

    @FunctionalInterface
    public interface Condition {
        boolean matches(ConditionContext context, AnnotatedTypeMetadata metadata);
    }
    

    条件装配 AutoConfigurationImportSelector.ConfigurationClassFilter#filter

    public class AutoConfigurationImportSelector implements DeferredImportSelector, BeanClassLoaderAware,
            ResourceLoaderAware, BeanFactoryAware, EnvironmentAware, Ordered {
    
        private static class ConfigurationClassFilter {
    
            private final List<AutoConfigurationImportFilter> filters;
    
            List<String> filter(List<String> configurations) {
                // ...
                for (AutoConfigurationImportFilter filter : this.filters) {
                    boolean[] match = filter.match(candidates, this.autoConfigurationMetadata);
                    // ...
            }
        }
    }
    
    public interface AutoConfigurationImportFilter {
        boolean[] match(String[] autoConfigurationClasses, AutoConfigurationMetadata autoConfigurationMetadata);
    }
    

    具体实现

    abstract class FilteringSpringBootCondition extends SpringBootCondition
            implements AutoConfigurationImportFilter, BeanFactoryAware, BeanClassLoaderAware {
    
        @Override
        public boolean[] match(String[] autoConfigurationClasses, AutoConfigurationMetadata autoConfigurationMetadata) {
            ConditionEvaluationReport report = ConditionEvaluationReport.find(this.beanFactory);
            ConditionOutcome[] outcomes = getOutcomes(autoConfigurationClasses, autoConfigurationMetadata);
            boolean[] match = new boolean[outcomes.length];
            for (int i = 0; i < outcomes.length; i++) {
                match[i] = (outcomes[i] == null || outcomes[i].isMatch());
                if (!match[i] && outcomes[i] != null) {
                    logOutcome(autoConfigurationClasses[i], outcomes[i]);
                    if (report != null) {
                        report.recordConditionEvaluation(autoConfigurationClasses[i], this, outcomes[i]);
                    }
                }
            }
            return match;
        }
    }
    

    相关文章

      网友评论

          本文标题:Spring 条件装配 Condition 分析

          本文链接:https://www.haomeiwen.com/subject/whaxndtx.html