springframework-scan(求指正)

文章目录

AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(BeanConfig.class);
ProductService productService = (ProductService) context.getBean("productFactoryBean");

AnnotationConfigApplicationContext

public AnnotationConfigApplicationContext(Class<?>... annotatedClasses) {
    this();
    this.register(annotatedClasses);
    this.refresh();
}

public AnnotationConfigApplicationContext() {
  this.reader = new AnnotatedBeanDefinitionReader(this);
  this.scanner = new ClassPathBeanDefinitionScanner(this);
}

refresh()

//刷新容器
public void refresh() throws BeansException, IllegalStateException {
    synchronized(this.startupShutdownMonitor) {
        this.prepareRefresh();
        ConfigurableListableBeanFactory beanFactory = this.obtainFreshBeanFactory();
        this.prepareBeanFactory(beanFactory);

        try {
            this.postProcessBeanFactory(beanFactory);
          //beanFactory准备好之后,执行beanPostProcessor,来对beanfactory进行处理
          //默认情况下,此时的beanfactory中的beanDefinitionMap有6个Beandefinition:即5个beandefinition+AppConfig的BeanDefinition。	而这6个中只有一个beanFactoryPostProcessor:ConfigurationCassPostProcessor。这里会执行ConfigurationCassPostProcessor来进行@Component扫描,扫描得到beanDefinition,并注册到beanFactory中
          //注意,扫描过程中可能会扫描到其他的BeanFactoryPostProcessor,那么这些BeanFactoryPostProcessor也必须在这一步进行
            this.invokeBeanFactoryPostProcessors(beanFactory);
            this.registerBeanPostProcessors(beanFactory);
            this.initMessageSource();
            this.initApplicationEventMulticaster();
            this.onRefresh();
            this.registerListeners();
          //完成bean工厂初始化
            this.finishBeanFactoryInitialization(beanFactory);
            this.finishRefresh();
        } catch (BeansException var9) {
            if (this.logger.isWarnEnabled()) {
                this.logger.warn("Exception encountered during context initialization - cancelling refresh attempt: " + var9);
            }

            this.destroyBeans();
            this.cancelRefresh(var9);
            throw var9;
        } finally {
            this.resetCommonCaches();
        }

    }
}

ClassPathBeanDefinitionScanner.class

//扫描包路径,对扫描到的类进行解析
//比如扫描到的类上@Component,就将这个类解析为BeanDefinition
public class ClassPathBeanDefinitionScanner extends ClassPathScanningCandidateComponentProvider {
  //用来注册、保存、移除、获取某个beanDefinition
    private final BeanDefinitionRegistry registry;
    private BeanDefinitionDefaults beanDefinitionDefaults;
    private String[] autowireCandidatePatterns;
    private BeanNameGenerator beanNameGenerator;
    private ScopeMetadataResolver scopeMetadataResolver;
    private boolean includeAnnotationConfig;
  
.......
  
    public int scan(String... basePackages) {
        int beanCountAtScanStart = this.registry.getBeanDefinitionCount();
        this.doScan(basePackages);
        if (this.includeAnnotationConfig) {
            AnnotationConfigUtils.registerAnnotationConfigProcessors(this.registry);
        }

        return this.registry.getBeanDefinitionCount() - beanCountAtScanStart;
    }

  //扫描逻辑
    protected Set<BeanDefinitionHolder> doScan(String... basePackages) {
        Assert.notEmpty(basePackages, "At least one base package must be specified");
        Set<BeanDefinitionHolder> beanDefinitions = new LinkedHashSet();
        String[] var3 = basePackages;
        int var4 = basePackages.length;

        for(int var5 = 0; var5 < var4; ++var5) {
            String basePackage = var3[var5];
          //核心扫描逻辑——>调用父类的findCandidateComponents方法
            Set<BeanDefinition> candidates = this.findCandidateComponents(basePackage);
          
            Iterator var8 = candidates.iterator();
						//遍历candidates
            while(var8.hasNext()) {
                BeanDefinition candidate = (BeanDefinition)var8.next();
              
              //解析@Scope注解
                ScopeMetadata scopeMetadata = this.scopeMetadataResolver.resolveScopeMetadata(candidate);
                candidate.setScope(scopeMetadata.getScopeName());
              
              //生成beanName
                String beanName = this.beanNameGenerator.generateBeanName(candidate, this.registry);
               
              //为beanDefinition设置一些默认值
              if (candidate instanceof AbstractBeanDefinition) {
                    this.postProcessBeanDefinition((AbstractBeanDefinition)candidate, beanName);
                }

                if (candidate instanceof AnnotatedBeanDefinition) {
              //解析@Lazy,@Primary,@DependOn,@Role,@Description,并将值设置给beanDefinition
 AnnotationConfigUtils.processCommonDefinitionAnnotations((AnnotatedBeanDefinition)candidate);
                }

              //检查容器中是否已经存在这个beanName
                if (this.checkCandidate(beanName, candidate)) {
                    BeanDefinitionHolder definitionHolder = new BeanDefinitionHolder(candidate, beanName);
                    definitionHolder = AnnotationConfigUtils.applyScopedProxyMode(scopeMetadata, definitionHolder, this.registry);
                    beanDefinitions.add(definitionHolder);
                  
                  //注册
                    this.registerBeanDefinition(definitionHolder, this.registry);
                }
            }
        }

        return beanDefinitions;
    }
  
  
  protected void postProcessBeanDefinition(AbstractBeanDefinition beanDefinition, String beanName) {
    
    //为beanDefinition设置一些默认值
    beanDefinition.applyDefaults(this.beanDefinitionDefaults);
    
    if (this.autowireCandidatePatterns != null) {
      beanDefinition.setAutowireCandidate(PatternMatchUtils.simpleMatch(this.autowireCandidatePatterns, beanName));
    }

  }

  protected void registerBeanDefinition(BeanDefinitionHolder definitionHolder, BeanDefinitionRegistry registry) {
    
      BeanDefinitionReaderUtils.registerBeanDefinition(definitionHolder, registry);
  }
  ......
registerBeanDefinition()
public static void registerBeanDefinition(BeanDefinitionHolder definitionHolder, BeanDefinitionRegistry registry) throws BeanDefinitionStoreException {
  
    String beanName = definitionHolder.getBeanName();
  //将beanName与beanDefinition注册到容器中,即注册到beanDefinitionMap中
    registry.registerBeanDefinition(beanName, definitionHolder.getBeanDefinition());
    String[] aliases = definitionHolder.getAliases();
    if (aliases != null) {
        String[] var4 = aliases;
        int var5 = aliases.length;

        for(int var6 = 0; var6 < var5; ++var6) {
            String alias = var4[var6];
            registry.registerAlias(beanName, alias);
        }
    }

}
registerBeanDefinition()
public void registerBeanDefinition(String beanName, BeanDefinition beanDefinition) throws BeanDefinitionStoreException {
  
    Assert.hasText(beanName, "Bean name must not be empty");
    Assert.notNull(beanDefinition, "BeanDefinition must not be null");
    if (beanDefinition instanceof AbstractBeanDefinition) {
        try {
            ((AbstractBeanDefinition)beanDefinition).validate();
        } catch (BeanDefinitionValidationException var9) {
            throw new BeanDefinitionStoreException(beanDefinition.getResourceDescription(), beanName, "Validation of bean definition failed", var9);
        }
    }

    BeanDefinition existingDefinition = (BeanDefinition)this.beanDefinitionMap.get(beanName);
    if (existingDefinition != null) {
        if (!this.isAllowBeanDefinitionOverriding()) {
            throw new BeanDefinitionStoreException(beanDefinition.getResourceDescription(), beanName, "Cannot register bean definition [" + beanDefinition + "] for bean '" + beanName + "': There is already [" + existingDefinition + "] bound.");
        }

        if (existingDefinition.getRole() < beanDefinition.getRole()) {
            if (this.logger.isWarnEnabled()) {
                this.logger.warn("Overriding user-defined bean definition for bean '" + beanName + "' with a framework-generated bean definition: replacing [" + existingDefinition + "] with [" + beanDefinition + "]");
            }
        } else if (!beanDefinition.equals(existingDefinition)) {
            if (this.logger.isInfoEnabled()) {
                this.logger.info("Overriding bean definition for bean '" + beanName + "' with a different definition: replacing [" + existingDefinition + "] with [" + beanDefinition + "]");
            }
        } else if (this.logger.isDebugEnabled()) {
            this.logger.debug("Overriding bean definition for bean '" + beanName + "' with an equivalent definition: replacing [" + existingDefinition + "] with [" + beanDefinition + "]");
        }
				
      //添加到beanDefinitionMap中
        this.beanDefinitionMap.put(beanName, beanDefinition);
    } else {
        if (this.hasBeanCreationStarted()) {
            synchronized(this.beanDefinitionMap) {
                this.beanDefinitionMap.put(beanName, beanDefinition);
                List<String> updatedDefinitions = new ArrayList(this.beanDefinitionNames.size() + 1);
                updatedDefinitions.addAll(this.beanDefinitionNames);
                updatedDefinitions.add(beanName);
                this.beanDefinitionNames = updatedDefinitions;
                if (this.manualSingletonNames.contains(beanName)) {
                    Set<String> updatedSingletons = new LinkedHashSet(this.manualSingletonNames);
                    updatedSingletons.remove(beanName);
                    this.manualSingletonNames = updatedSingletons;
                }
            }
        } else {
            this.beanDefinitionMap.put(beanName, beanDefinition);
            this.beanDefinitionNames.add(beanName);
            this.manualSingletonNames.remove(beanName);
        }

        this.frozenBeanDefinitionNames = null;
    }

    if (existingDefinition != null || this.containsSingleton(beanName)) {
        this.resetBeanDefinition(beanName);
    }

}
checkCandidate()
protected boolean checkCandidate(String beanName, BeanDefinition beanDefinition) throws IllegalStateException {
  
    if (!this.registry.containsBeanDefinition(beanName)) {
        return true;
    } else {
        BeanDefinition existingDef = this.registry.getBeanDefinition(beanName);
        BeanDefinition originatingDef = existingDef.getOriginatingBeanDefinition();
        if (originatingDef != null) {
            existingDef = originatingDef;
        }
				
      //是否兼容,如果兼容则返回false,否则直接抛异常
        if (this.isCompatible(beanDefinition, existingDef)) {
            return false;
        } else {
            throw new ConflictingBeanDefinitionException("Annotation-specified bean name '" + beanName + "' for bean class [" + beanDefinition.getBeanClassName() + "] conflicts with existing, non-compatible bean definition of same name and class [" + existingDef.getBeanClassName() + "]");
        }
    }
}
isCompatible()
protected boolean isCompatible(BeanDefinition newDefinition, BeanDefinition existingDefinition) {
    //通过判断beanDefinition以及resource来判断是否冲突
  return !(existingDefinition instanceof ScannedGenericBeanDefinition) || newDefinition.getSource().equals(existingDefinition.getSource()) || newDefinition.equals(existingDefinition);
}
processCommonDefinitionAnnotations()
public static void processCommonDefinitionAnnotations(AnnotatedBeanDefinition abd) {
  
  processCommonDefinitionAnnotations(abd, abd.getMetadata());
}

static void processCommonDefinitionAnnotations(AnnotatedBeanDefinition abd, AnnotatedTypeMetadata metadata) {
  
    if (metadata.isAnnotated(Lazy.class.getName())) {
        abd.setLazyInit(attributesFor(metadata, Lazy.class).getBoolean("value"));
    } else if (abd.getMetadata() != metadata && abd.getMetadata().isAnnotated(Lazy.class.getName())) {
        abd.setLazyInit(attributesFor(abd.getMetadata(), (Class)Lazy.class).getBoolean("value"));
    }

    if (metadata.isAnnotated(Primary.class.getName())) {
        abd.setPrimary(true);
    }

    if (metadata.isAnnotated(DependsOn.class.getName())) {
        abd.setDependsOn(attributesFor(metadata, DependsOn.class).getStringArray("value"));
    }

    if (abd instanceof AbstractBeanDefinition) {
        AbstractBeanDefinition absBd = (AbstractBeanDefinition)abd;
        if (metadata.isAnnotated(Role.class.getName())) {
            absBd.setRole(attributesFor(metadata, Role.class).getNumber("value").intValue());
        }

        if (metadata.isAnnotated(Description.class.getName())) {
            absBd.setDescription(attributesFor(metadata, Description.class).getString("value"));
        }
    }

}
applyDefaults()
public void applyDefaults(BeanDefinitionDefaults defaults) {
  
    this.setLazyInit(defaults.isLazyInit());
    this.setAutowireMode(defaults.getAutowireMode());
    this.setDependencyCheck(defaults.getDependencyCheck());
    this.setInitMethodName(defaults.getInitMethodName());
    this.setEnforceInitMethod(false);
    this.setDestroyMethodName(defaults.getDestroyMethodName());
    this.setEnforceDestroyMethod(false);
}
generateBeanName()
public String generateBeanName(BeanDefinition definition, BeanDefinitionRegistry registry) {
  
  //获取注解中指定的beanName 
  if (definition instanceof AnnotatedBeanDefinition) {
        String beanName = this.determineBeanNameFromAnnotation((AnnotatedBeanDefinition)definition);
        if (StringUtils.hasText(beanName)) {
            return beanName;
        }
    }

  //构造一个默认的beanName
    return this.buildDefaultBeanName(definition, registry);
}
determineBeanNameFromAnnotation()
protected String determineBeanNameFromAnnotation(AnnotatedBeanDefinition annotatedDef) {
  
    AnnotationMetadata amd = annotatedDef.getMetadata();
  //获取注解集合
    Set<String> types = amd.getAnnotationTypes();
    String beanName = null;
    Iterator var5 = types.iterator();
//遍历注解
    while(var5.hasNext()) {
        String type = (String)var5.next();
        AnnotationAttributes attributes = AnnotationConfigUtils.attributesFor(amd, type);
      //判断是否是@Component注解 
      if (this.isStereotypeWithNameValue(type, amd.getMetaAnnotationTypes(type), attributes)) {
        		//获取注解的value值
            Object value = attributes.get("value");
            if (value instanceof String) {
                String strVal = (String)value;
                if (StringUtils.hasLength(strVal)) {
                    if (beanName != null && !strVal.equals(beanName)) {
                        throw new IllegalStateException("Stereotype annotations suggest inconsistent component names: '" + beanName + "' versus '" + strVal + "'");
                    }

                    beanName = strVal;
                }
            }
        }
    }

    return beanName;
}

protected boolean isStereotypeWithNameValue(String annotationType, Set<String> metaAnnotationTypes, Map<String, Object> attributes) {
    boolean isStereotype = annotationType.equals("org.springframework.stereotype.Component") || metaAnnotationTypes != null && metaAnnotationTypes.contains("org.springframework.stereotype.Component") || annotationType.equals("javax.annotation.ManagedBean") || annotationType.equals("javax.inject.Named");
    return isStereotype && attributes != null && attributes.containsKey("value");
}
decapitalize()
public static String decapitalize(String name) {
  // //如果为空,则直接返回
    if (name == null || name.length() == 0) {
        return name;
    }
  //如果字符大于1且第一二个字符大写,则直接返回
    if (name.length() > 1 && Character.isUpperCase(name.charAt(1)) &&
                    Character.isUpperCase(name.charAt(0))){
        return name;
    }
   //否则将第一个字符转为小写再返回
    char chars[] = name.toCharArray();
    chars[0] = Character.toLowerCase(chars[0]);
    return new String(chars);
}
resolveBasePackage()
protected String resolveBasePackage(String basePackage) {
  return ClassUtils.convertClassNameToResourcePath(this.environment.resolveRequiredPlaceholders(basePackage));
}

public static String convertClassNameToResourcePath(String className) {
  Assert.notNull(className, "Class name must not be null");
  return className.replace('.', '/');
}
findCandidateComponents()
public Set<BeanDefinition> findCandidateComponents(String basePackage) {
  //结果集
    LinkedHashSet candidates = new LinkedHashSet();

    try {
      //拼接包路径
      //resolveBasePackage——>replace('.', '/')
      //this.resourcePattern = "**/*.class";
        String packageSearchPath = "classpath*:" + this.resolveBasePackage(basePackage) + '/' + this.resourcePattern;
      //Resource:扫描出来的一个个class的File对象
        Resource[] resources = this.resourcePatternResolver.getResources(packageSearchPath);
        boolean traceEnabled = this.logger.isTraceEnabled();
        boolean debugEnabled = this.logger.isDebugEnabled();
        Resource[] var7 = resources;
        int var8 = resources.length;

        for(int var9 = 0; var9 < var8; ++var9) {
            Resource resource = var7[var9];
            if (traceEnabled) {
                this.logger.trace("Scanning " + resource);
            }

            if (resource.isReadable()) {
                try {
                  //获取该类的元数据读取器
                  //MetadataReader——>读取类名、类中的方法、类上的注解<——ASM技术
                    MetadataReader metadataReader = this.metadataReaderFactory.getMetadataReader(resource);
                  //判断当前类是不是一个bean
                  //excludeFilters、includeFilters判断
                    if (this.isCandidateComponent(metadataReader)) {
                      //如果符合以上条件,就构造一个BeanDefinition
                        ScannedGenericBeanDefinition sbd = new ScannedGenericBeanDefinition(metadataReader);
                        sbd.setResource(resource);
                        sbd.setSource(resource);
                        if (this.isCandidateComponent((AnnotatedBeanDefinition)sbd)) {
                            if (debugEnabled) {
                                this.logger.debug("Identified candidate component class: " + resource);
                            }
														//将BeanDefinition加入到结果集中
                            candidates.add(sbd);
                        } else if (debugEnabled) {
                            this.logger.debug("Ignored because not a concrete top-level class: " + resource);
                        }
                    } else if (traceEnabled) {
                        this.logger.trace("Ignored because not matching any filter: " + resource);
                    }
                } catch (Throwable var13) {
                    throw new BeanDefinitionStoreException("Failed to read candidate component class: " + resource, var13);
                }
            } else if (traceEnabled) {
                this.logger.trace("Ignored because not readable: " + resource);
            }
        }
				//返回结果集
        return candidates;
    } catch (IOException var14) {
        throw new BeanDefinitionStoreException("I/O failure during classpath scanning", var14);
    }
}
isCandidateComponent
protected boolean isCandidateComponent(MetadataReader metadataReader) throws IOException {
    Iterator var2 = this.excludeFilters.iterator();

    TypeFilter tf;
    do {
        if (!var2.hasNext()) {
            var2 = this.includeFilters.iterator();

            do {
                if (!var2.hasNext()) {
                    return false;
                }

                tf = (TypeFilter)var2.next();
            } while(!tf.match(metadataReader, this.metadataReaderFactory));
              //符合includeFilters的才会进行Condition匹配,通过之后才能成为Bean
              //也就是先判断是否有@Component注解,再看是否符合@Conditional中的业务逻辑
            return this.isConditionMatch(metadataReader);
        }

        tf = (TypeFilter)var2.next();
      //当前类只要与任意一个excludeFilters中的类匹配了,就返回false
    } while(!tf.match(metadataReader, this.metadataReaderFactory));

    return false;
}
  • isConditionMatch()

    private boolean isConditionMatch(MetadataReader metadataReader) {
        if (this.conditionEvaluator == null) {
            this.conditionEvaluator = new ConditionEvaluator(this.getRegistry(), this.getEnvironment(), this.getResourceLoader());
        }
    //是否要跳过
        return !this.conditionEvaluator.shouldSkip(metadataReader.getAnnotationMetadata()//获取类上的注解信息);
    }
    
    • shouldSkip()
    public boolean shouldSkip(AnnotatedTypeMetadata metadata) {
        return this.shouldSkip(metadata, (ConfigurationPhase)null);
    }
    
    public boolean shouldSkip(AnnotatedTypeMetadata metadata, ConfigurationPhase phase) {
        if (metadata != null && metadata.isAnnotated(Conditional.class.getName())) {
           
          //获取@Conditional指定的类,执行其matches()方法
          if (phase == null) {
                return metadata instanceof AnnotationMetadata && ConfigurationClassUtils.isConfigurationCandidate((AnnotationMetadata)metadata) ? this.shouldSkip(metadata, ConfigurationPhase.PARSE_CONFIGURATION) : this.shouldSkip(metadata, ConfigurationPhase.REGISTER_BEAN);
            } else {
                List<Condition> conditions = new ArrayList();
                Iterator var4 = this.getConditionClasses(metadata).iterator();
    
                while(var4.hasNext()) {
                    String[] conditionClasses = (String[])var4.next();
                    String[] var6 = conditionClasses;
                    int var7 = conditionClasses.length;
    
                    for(int var8 = 0; var8 < var7; ++var8) {
                        String conditionClass = var6[var8];
                        Condition condition = this.getCondition(conditionClass, this.context.getClassLoader());
                        conditions.add(condition);
                    }
                }
    
                AnnotationAwareOrderComparator.sort(conditions);
                var4 = conditions.iterator();
    
                Condition condition;
                ConfigurationPhase requiredPhase;
                do {
                    do {
                        if (!var4.hasNext()) {
                            return false;
                        }
    
                        condition = (Condition)var4.next();
                        requiredPhase = null;
                        if (condition instanceof ConfigurationCondition) {
                            requiredPhase = ((ConfigurationCondition)condition).getConfigurationPhase();
                        }
                    } while(requiredPhase != null && requiredPhase != phase);
                } while(condition.matches(this.context, metadata));
    
                return true;
            }
          
        } else {
            return false;
        }
    }
    
ScannedGenericBeanDefinition()
public ScannedGenericBeanDefinition(MetadataReader metadataReader) {
    Assert.notNull(metadataReader, "MetadataReader must not be null");
    this.metadata = metadataReader.getAnnotationMetadata();
    //将类名设置为beanClass,而不是Class本身
  //原因:Spring是利用ASM技术来扫描这个类的,而非解析这个类
  //真正创建这个bean的时候才会将这个Class对象赋值给beanClass
    this.setBeanClassName(this.metadata.getClassName());
}
  • setBeanClassName()

    //Object类型,而非Class类型
    private volatile Object beanClass;
    
    public void setBeanClassName(String beanClassName) {
        this.beanClass = beanClassName;
    }
    
isCandidateComponent()
protected boolean isCandidateComponent(AnnotatedBeanDefinition beanDefinition) {
    AnnotationMetadata metadata = beanDefinition.getMetadata();
    return metadata.isIndependent() && (metadata.isConcrete() || metadata.isAbstract() && metadata.hasAnnotatedMethods(Lookup.class.getName()));
}
  • isIndependent()
//该类是否独立
boolean isIndependent();
  • isConcrete()
//该类不是接口并且也不是抽象类
boolean isConcrete();

public boolean isConcrete() {
  return !this.isInterface && !this.isAbstract;
}
  • hasAnnotatedMethods(Lookup.class.getName())

    //该类是否有方法被@Lookup方法标注	
    boolean hasAnnotatedMethods(String var1);
    
  • isAbstract()

    //该类是抽象类
    boolean isAbstract();
    
上一篇:LeetCode 1219. 黄金矿工


下一篇:leetcode--20.有效的括号