Spring源码分析之组件扫描(下)

本文深入探讨Spring框架中Bean定义的解析流程,包括注解处理、依赖注入、作用域代理模式、事件发布等关键步骤,揭示了Spring如何管理Bean的生命周期。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

名字获取成功后,判断bean定义是那种类型,如果是注解类型的话,就解析以下这些属性


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(), 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"));
    }
  }
}

检查bean定义是否已经存在于注册中心中


protected boolean checkCandidate(String beanName, BeanDefinition beanDefinition) throws IllegalStateException {
  if (!this.registry.containsBeanDefinition(beanName)) {
    return true;
  }
  BeanDefinition existingDef = this.registry.getBeanDefinition(beanName);
  BeanDefinition originatingDef = existingDef.getOriginatingBeanDefinition();
  if (originatingDef != null) {
    existingDef = originatingDef;
  }
  if (isCompatible(beanDefinition, existingDef)) {
    return false;
  }
  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() + "]");
}

创建bean定义持有类,判断是否是代理模式


static BeanDefinitionHolder applyScopedProxyMode(
    ScopeMetadata metadata, BeanDefinitionHolder definition, BeanDefinitionRegistry registry) {

  ScopedProxyMode scopedProxyMode = metadata.getScopedProxyMode();
  if (scopedProxyMode.equals(ScopedProxyMode.NO)) {
    return definition;
  }
  boolean proxyTargetClass = scopedProxyMode.equals(ScopedProxyMode.TARGET_CLASS);
  return ScopedProxyCreator.createScopedProxy(definition, registry, proxyTargetClass);
}

最后把该bean定义注册到注册中心中


protected void registerBeanDefinition(BeanDefinitionHolder definitionHolder, BeanDefinitionRegistry registry) {
  BeanDefinitionReaderUtils.registerBeanDefinition(definitionHolder, registry);
}

public static void registerBeanDefinition(
    BeanDefinitionHolder definitionHolder, BeanDefinitionRegistry registry)
    throws BeanDefinitionStoreException {

  // Register bean definition under primary name.
  String beanName = definitionHolder.getBeanName();
  registry.registerBeanDefinition(beanName, definitionHolder.getBeanDefinition());

  // Register aliases for bean name, if any.
  String[] aliases = definitionHolder.getAliases();
  if (aliases != null) {
    for (String alias : aliases) {
      registry.registerAlias(beanName, alias);
    }
  }
}

发布组件注册事件


protected void registerComponents(
      XmlReaderContext readerContext, Set<BeanDefinitionHolder> beanDefinitions, Element element) {

  Object source = readerContext.extractSource(element);
  CompositeComponentDefinition compositeDef = new CompositeComponentDefinition(element.getTagName(), source);

  for (BeanDefinitionHolder beanDefHolder : beanDefinitions) {
    compositeDef.addNestedComponent(new BeanComponentDefinition(beanDefHolder));
  }

  // Register annotation config processors, if necessary.
  boolean annotationConfig = true;
  if (element.hasAttribute(ANNOTATION_CONFIG_ATTRIBUTE)) {
    annotationConfig = Boolean.valueOf(element.getAttribute(ANNOTATION_CONFIG_ATTRIBUTE));
  }
  if (annotationConfig) {
    Set<BeanDefinitionHolder> processorDefinitions =
        AnnotationConfigUtils.registerAnnotationConfigProcessors(readerContext.getRegistry(), source);
    for (BeanDefinitionHolder processorDefinition : processorDefinitions) {
      compositeDef.addNestedComponent(new BeanComponentDefinition(processorDefinition));
    }
  }

  readerContext.fireComponentRegistered(compositeDef);
}

 

判断是否带有属性annotation-config,默认需要解析注解配置,获取bean工厂,设置依赖比较器,注解装配解析器


DefaultListableBeanFactory beanFactory = unwrapDefaultListableBeanFactory(registry);
if (beanFactory != null) {
  if (!(beanFactory.getDependencyComparator() instanceof AnnotationAwareOrderComparator)) {
    beanFactory.setDependencyComparator(AnnotationAwareOrderComparator.INSTANCE);
  }
  if (!(beanFactory.getAutowireCandidateResolver() instanceof ContextAnnotationAutowireCandidateResolver)) {
    beanFactory.setAutowireCandidateResolver(new ContextAnnotationAutowireCandidateResolver());
  }
}

注册配置类处理器,它实现了接口BeanDefinitionRegistryPostProcessor


Set<BeanDefinitionHolder> beanDefs = new LinkedHashSet<BeanDefinitionHolder>(4);
if (!registry.containsBeanDefinition(CONFIGURATION_ANNOTATION_PROCESSOR_BEAN_NAME)) {
  RootBeanDefinition def = new RootBeanDefinition(ConfigurationClassPostProcessor.class);
  def.setSource(source);
  beanDefs.add(registerPostProcessor(registry, def, CONFIGURATION_ANNOTATION_PROCESSOR_BEAN_NAME));
}

private static BeanDefinitionHolder registerPostProcessor(
      BeanDefinitionRegistry registry, RootBeanDefinition definition, String beanName) {

  definition.setRole(BeanDefinition.ROLE_INFRASTRUCTURE);
  registry.registerBeanDefinition(beanName, definition);
  return new BeanDefinitionHolder(definition, beanName);
}

处理bean定义注册方法,首先注册两个bean定义处理器


public void postProcessBeanDefinitionRegistry(BeanDefinitionRegistry registry) {
  RootBeanDefinition iabpp = new RootBeanDefinition(ImportAwareBeanPostProcessor.class);
  iabpp.setRole(BeanDefinition.ROLE_INFRASTRUCTURE);
  registry.registerBeanDefinition(IMPORT_AWARE_PROCESSOR_BEAN_NAME, iabpp);

  RootBeanDefinition ecbpp = new RootBeanDefinition(EnhancedConfigurationBeanPostProcessor.class);
  ecbpp.setRole(BeanDefinition.ROLE_INFRASTRUCTURE);
  registry.registerBeanDefinition(ENHANCED_CONFIGURATION_PROCESSOR_BEAN_NAME, ecbpp);

  int registryId = System.identityHashCode(registry);
  if (this.registriesPostProcessed.contains(registryId)) {
    throw new IllegalStateException(
        "postProcessBeanDefinitionRegistry already called on this post-processor against " + registry);
  }
  if (this.factoriesPostProcessed.contains(registryId)) {
    throw new IllegalStateException(
        "postProcessBeanFactory already called on this post-processor against " + registry);
  }
  this.registriesPostProcessed.add(registryId);

  processConfigBeanDefinitions(registry);
}

处理bean定义配置信息,首先获取注册中心的所有bean定义名字,判断配置类类型是完整的full还是部分的lite

List<BeanDefinitionHolder> configCandidates = new ArrayList<BeanDefinitionHolder>();
String[] candidateNames = registry.getBeanDefinitionNames();

for (String beanName : candidateNames) {
  BeanDefinition beanDef = registry.getBeanDefinition(beanName);
  if (ConfigurationClassUtils.isFullConfigurationClass(beanDef) ||
      ConfigurationClassUtils.isLiteConfigurationClass(beanDef)) {
    if (logger.isDebugEnabled()) {
      logger.debug("Bean definition has already been processed as a configuration class: " + beanDef);
    }
  }
  else if (ConfigurationClassUtils.checkConfigurationClassCandidate(beanDef, this.metadataReaderFactory)) {
    configCandidates.add(new BeanDefinitionHolder(beanDef, beanName));
  }
}

具体解析bean类型配置,当bean元数据上带有注解Configuration的为full类型


public static boolean checkConfigurationClassCandidate(BeanDefinition beanDef, MetadataReaderFactory metadataReaderFactory) {
  String className = beanDef.getBeanClassName();
  if (className == null) {
    return false;
  }

  AnnotationMetadata metadata;
  if (beanDef instanceof AnnotatedBeanDefinition &&
      className.equals(((AnnotatedBeanDefinition) beanDef).getMetadata().getClassName())) {
    // Can reuse the pre-parsed metadata from the given BeanDefinition...
    metadata = ((AnnotatedBeanDefinition) beanDef).getMetadata();
  }
  else if (beanDef instanceof AbstractBeanDefinition && ((AbstractBeanDefinition) beanDef).hasBeanClass()) {
    // Check already loaded Class if present...
    // since we possibly can't even load the class file for this Class.
    Class<?> beanClass = ((AbstractBeanDefinition) beanDef).getBeanClass();
    metadata = new StandardAnnotationMetadata(beanClass, true);
  }
  else {
    try {
      MetadataReader metadataReader = metadataReaderFactory.getMetadataReader(className);
      metadata = metadataReader.getAnnotationMetadata();
    }
    catch (IOException ex) {
      if (logger.isDebugEnabled()) {
        logger.debug("Could not find class file for introspecting configuration annotations: " + className, ex);
      }
      return false;
    }
  }

  if (isFullConfigurationCandidate(metadata)) {
    beanDef.setAttribute(CONFIGURATION_CLASS_ATTRIBUTE, CONFIGURATION_CLASS_FULL);
  }
  else if (isLiteConfigurationCandidate(metadata)) {
    beanDef.setAttribute(CONFIGURATION_CLASS_ATTRIBUTE, CONFIGURATION_CLASS_LITE);
  }
  else {
    return false;
  }

  // It's a full or lite configuration candidate... Let's determine the order value, if any.
  Map<String, Object> orderAttributes = metadata.getAnnotationAttributes(Order.class.getName());
  if (orderAttributes != null) {
    beanDef.setAttribute(ORDER_ATTRIBUTE, orderAttributes.get(AnnotationUtils.VALUE));
  }

  return true;
}

lite类型类型包含以下几种注解,最后解析注解Order上带有序列值


static {
  candidateIndicators.add(Component.class.getName());
  candidateIndicators.add(ComponentScan.class.getName());
  candidateIndicators.add(Import.class.getName());
  candidateIndicators.add(ImportResource.class.getName());
}

public static boolean isLiteConfigurationCandidate(AnnotationMetadata metadata) {
  // Do not consider an interface or an annotation...
  if (metadata.isInterface()) {
    return false;
  }

  // Any of the typical annotations found?
  for (String indicator : candidateIndicators) {
    if (metadata.isAnnotated(indicator)) {
      return true;
    }
  }

  // Finally, let's look for @Bean methods...
  try {
    return metadata.hasAnnotatedMethods(Bean.class.getName());
  }
  catch (Throwable ex) {
    if (logger.isDebugEnabled()) {
      logger.debug("Failed to introspect @Bean methods on class [" + metadata.getClassName() + "]: " + ex);
    }
    return false;
  }
}

判断是否有满足条件的bean配置,并进行排序,没有Order注解的默认为最大数字,即排序值最低

// Return immediately if no @Configuration classes were found
if (configCandidates.isEmpty()) {
  return;
}

// Sort by previously determined @Order value, if applicable
Collections.sort(configCandidates, new Comparator<BeanDefinitionHolder>() {
  @Override
  public int compare(BeanDefinitionHolder bd1, BeanDefinitionHolder bd2) {
    int i1 = ConfigurationClassUtils.getOrder(bd1.getBeanDefinition());
    int i2 = ConfigurationClassUtils.getOrder(bd2.getBeanDefinition());
    return (i1 < i2) ? -1 : (i1 > i2) ? 1 : 0;
  }
});

检测应用程序上下文是否有自定义bean名称生成策略


// Detect any custom bean name generation strategy supplied through the enclosing application context
SingletonBeanRegistry singletonRegistry = null;
if (registry instanceof SingletonBeanRegistry) {
  singletonRegistry = (SingletonBeanRegistry) registry;
  if (!this.localBeanNameGeneratorSet && singletonRegistry.containsSingleton(CONFIGURATION_BEAN_NAME_GENERATOR)) {
    BeanNameGenerator generator = (BeanNameGenerator) singletonRegistry.getSingleton(CONFIGURATION_BEAN_NAME_GENERATOR);
    this.componentScanBeanNameGenerator = generator;
    this.importBeanNameGenerator = generator;
  }
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值