跳至主要內容

属性源原理解析3

wangdx大约 20 分钟

Aware 依赖注入管理

Aware 依赖注入实现

  • 在进行传统的操作配置时,所有需要进行依赖注入的操作类都必须使用“@Autowired”注解进行处理,而为了进行更加详细的 Bean 注入配置管理,Spring 提供了一个 Aware 的处理接口,利用该接口可以通过自定义的 setXxx()处理形式获取到指定 Bean 的对象实例
1、
package com.yootk.aware.source;

public class DatabaseConfig { //  随意定义的一个程序类
    private String name; // 保存数据库的名称
    private String url; // 保存数据库的处理路径
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public String getUrl() {
        return url;
    }
    public void setUrl(String url) {
        this.url = url;
    }

    @Override
    public String toString() {
        return "【DatabaseConfig】name = " + this.name + "、url = " + this.url;
    }
}


2、
package com.yootk.aware.bind;

import com.yootk.aware.source.DatabaseConfig;
import org.springframework.beans.factory.Aware;

public interface IDatabaseAware extends Aware { // 仅仅做为一个标记
    public void setDatabaseConfig(DatabaseConfig config); // 自动注入DatabaseConfig实例
}


3、
package com.yootk.aware.post;

import com.yootk.aware.bind.IDatabaseAware;
import com.yootk.aware.source.DatabaseConfig;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.BeanPostProcessor;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;

public class DatabaseConfigAwareBeanPostProcessor
    implements BeanPostProcessor, ApplicationContextAware {
    private ApplicationContext applicationContext;
    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        // 在程序启动的时候,自动的注入ApplicationContext对象实例,有了它就有了Spring的一切
        this.applicationContext = applicationContext;
    }
    @Override
    public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
        Object config = this.applicationContext.getBean("databaseConfig"); //  获取指定对象
        if (config == null) {   // 已经在容器之中注册了此Bean实例
            return bean; // 直接返回当前的Bean
        }
        // IDatabaseAware接口子类对象实例之中,一定要注入DatabaseConfig对象
        if (config instanceof DatabaseConfig && bean instanceof IDatabaseAware) {
            ((IDatabaseAware) bean).setDatabaseConfig((DatabaseConfig) config); // 依赖配置
        }
        return bean;
    }
}


4、
package com.yootk.aware.impl;

import com.yootk.aware.bind.IDatabaseAware;
import com.yootk.aware.source.DatabaseConfig;

public class YootkDatabase implements IDatabaseAware { // 定义接口实现子类
    private DatabaseConfig config;
    @Override
    public void setDatabaseConfig(DatabaseConfig config) {
        this.config = config;
    }
    public DatabaseConfig getConfig() {
        return config;
    }
}


5、
package com.yootk.aware.config;

import com.yootk.aware.impl.YootkDatabase;
import com.yootk.aware.post.DatabaseConfigAwareBeanPostProcessor;
import com.yootk.aware.source.DatabaseConfig;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
public class AwareMessageConfig {
    @Bean
    public DatabaseConfig databaseConfig() {
        DatabaseConfig config = new DatabaseConfig();
        config.setName("yootk.database");
        config.setUrl("www.yootk.com/mysql");
        return config;
    }
    @Bean
    public YootkDatabase yootkDatabase() {
        return new YootkDatabase();
    }
    @Bean
    public DatabaseConfigAwareBeanPostProcessor databaseConfigAwareBeanPostProcessor() {
        return new DatabaseConfigAwareBeanPostProcessor();
    }
}


6、
package com.yootk.main;

import com.yootk.aware.impl.YootkDatabase;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;

public class StartYootkSpringApplication { // Spring容器的启动类
    private static final Logger LOGGER =
            LoggerFactory.getLogger(StartYootkSpringApplication.class);
    public static void main(String[] args) throws Exception {
        AnnotationConfigApplicationContext context =
                new AnnotationConfigApplicationContext(); // 注解方式来启动Spring容器
        context.scan("com.yootk.aware"); //  配置扫描包
        context.refresh(); // 刷新操作
        YootkDatabase database = context.getBean(YootkDatabase.class);
        LOGGER.info("{}", database.getConfig());
    }
}

ApplicationContextAwareProcessor

ApplicationContextAwareProcessor

  • 在 Spring 中为了内置 Bean 的数据处理方便,提供了一系列的 Aware 子接口,而通过之前的分析可以发现,要想更好的处理每一个 Aware 子接口,往往都需要定义有一个与之匹配的 BeanPostProcessor 子类。为了简化这些内置 Bean 的注入管理操作,Spring 提供了-个 ApplicationContextAwareProcessor 处理子类
1、
package org.springframework.context.support;
class ApplicationContextAwareProcessor implements BeanPostProcessor {
   // ApplicationContext有一个终极的实现子类 —— AbstractApplicatonContext。
   private final ConfigurableApplicationContext applicationContext; // 应用上下文
   private final StringValueResolver embeddedValueResolver; // 数据解析功能
   public ApplicationContextAwareProcessor(
ConfigurableApplicationContext applicationContext) { // 接收ApplicationContext
      this.applicationContext = applicationContext; // 对象的保存
      this.embeddedValueResolver =
new EmbeddedValueResolver(applicationContext.getBeanFactory());// 实例化
   }
   @Override
   @Nullable
   public Object postProcessBeforeInitialization(// Bean初始化之前进行调用
Object bean, String beanName) throws BeansException {
      if (!(bean instanceof EnvironmentAware || bean instanceof EmbeddedValueResolverAware ||
            bean instanceof ResourceLoaderAware ||
bean instanceof ApplicationEventPublisherAware ||
            bean instanceof MessageSourceAware || bean instanceof ApplicationContextAware ||
            bean instanceof ApplicationStartupAware)) {
         return bean; // 如果Bean都不满足,直接返回
      }
      invokeAwareInterfaces(bean); // Aware接口方法调用
      return bean;
   }
   private void invokeAwareInterfaces(Object bean) { // 核心处理
      if (bean instanceof EnvironmentAware) { // 判断类型
         ((EnvironmentAware) bean).setEnvironment(this.applicationContext.getEnvironment());
      }
      if (bean instanceof EmbeddedValueResolverAware) {
         ((EmbeddedValueResolverAware) bean)
.setEmbeddedValueResolver(this.embeddedValueResolver);
      }
      if (bean instanceof ResourceLoaderAware) {
         ((ResourceLoaderAware) bean).setResourceLoader(this.applicationContext);
      }
      if (bean instanceof ApplicationEventPublisherAware) {
         ((ApplicationEventPublisherAware) bean)
.setApplicationEventPublisher(this.applicationContext);
      }
      if (bean instanceof MessageSourceAware) {
         ((MessageSourceAware) bean).setMessageSource(this.applicationContext);
      }
      if (bean instanceof ApplicationStartupAware) {
         ((ApplicationStartupAware) bean).setApplicationStartup(this.applicationContext.getApplicationStartup());
      }
      if (bean instanceof ApplicationContextAware) { // 通过这个判断实现了Spring上下文实例注入
         ((ApplicationContextAware) bean).setApplicationContext(this.applicationContext);
      }
   }
}

Spring 配置文件路径处理

XML 配置文件解析结构

一个类如果要想通过Spring容器进行Bean对象实例的维护,可以通过XML配置文件的形式进行定义,而此配置文件要通过ClassPathXmlApplicationContext或FileSystemXmlApplicationContext类才可以解析

  ClassPathXmlApplicationContext(CLASSPATH下加载XML配置文件启动).
    public class FileSystemXmlApplicationContext extends AbstractXmlApplicationContext {}
  FileSystemXmlApplicationContext(任意磁盘路径下加载 XML配置文件启动).
    public class ClassPathXmlApplicationContext extends AbstractXmlApplicationContext {}

ClassPathXmlApplicationContext

AbstractXmlApplicationContext

AbstractRefreshableConfigApplicationContext

  • setConfigLocations
  • resolvePath
1、
public class ClassPathXmlApplicationContext
extends AbstractXmlApplicationContext {}
public class FileSystemXmlApplicationContext
extends AbstractXmlApplicationContext {}


2、
public abstract class AbstractXmlApplicationContext
extends AbstractRefreshableConfigApplicationContext
public abstract class AbstractRefreshableConfigApplicationContext
extends AbstractRefreshableApplicationContext
      implements BeanNameAware, InitializingBean {}
public abstract class AbstractRefreshableApplicationContext
extends AbstractApplicationContext
public abstract class AbstractApplicationContext extends DefaultResourceLoader
      implements ConfigurableApplicationContext
public interface ConfigurableApplicationContext
extends ApplicationContext, Lifecycle, Closeable
public interface ApplicationContext
extends EnvironmentCapable, ListableBeanFactory, HierarchicalBeanFactory,
                MessageSource, ApplicationEventPublisher, ResourcePatternResolver


3、
package com.yootk.main;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.support.AbstractRefreshableApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import java.lang.reflect.Field;
import java.util.Arrays;

public class GetConfigLocations { // Spring容器的启动类
    private static final Logger LOGGER =
            LoggerFactory.getLogger(GetConfigLocations.class);
    public static void main(String[] args) throws Exception {
        AbstractRefreshableApplicationContext context =
                new ClassPathXmlApplicationContext("classpath:spring/spring-*.xml");
        // 由于该类中没有提供获取全部解析路径的方法,所以可以考虑使用反射的方式进行处理
        Class<?> clazz = context.getClass(); // 获取当前的程序类
        Field field = getFieldOfClass(clazz, "configLocations"); // 获取指定的属性
        field.setAccessible(true); //  解除包装
        String [] configLocations = (String []) field.get(context);
        LOGGER.info("配置文件存储:{}", Arrays.toString(configLocations));
    }
    public static Field getFieldOfClass(Class<?> clazz, String filedName) {
        Field field = null;
        while(field == null) {  // 没有获取到成员对象
            try {
                field = clazz.getDeclaredField(filedName); // 获取成员属性
                break; // 接相互当前的循环
            } catch (NoSuchFieldException e) { // 产生异常
                clazz = clazz.getSuperclass(); // 本类没有此属性,获取父类实例
                if (clazz == null) { // 没有父类
                    break;
                }
            }
        }
        return field;
    }
}

刷新 Spring 上下文

1、
@Override
public void refresh() throws BeansException, IllegalStateException {
   synchronized (this.startupShutdownMonitor) {  // 刷新的时候进行同步处理
      // 启动步骤的记录,因为不同的操作会有不同的启动步骤,这里面主要做一个标记
      StartupStep contextRefresh = this.applicationStartup.start("spring.context.refresh");
      // Prepare this context for refreshing.
      prepareRefresh();             // 准备执行刷新处理
      // Tell the subclass to refresh the internal bean factory.
      ConfigurableListableBeanFactory beanFactory = obtainFreshBeanFactory();// 获取Bean工厂
      // Prepare the bean factory for use in this context.
      prepareBeanFactory(beanFactory); // BeanFactory初始化,BeanFactory初始化完了
      try {
         // Allows post-processing of the bean factory in context subclasses.
         postProcessBeanFactory(beanFactory); // BeanFactoryPostProcessor处理接口
         StartupStep beanPostProcess =
this.applicationStartup.start("spring.context.beans.post-process"); // 步骤记录
         // Invoke factory processors registered as beans in the context.
         invokeBeanFactoryPostProcessors(beanFactory); // 执行BeanFactoryPostProcessor子类
         // Register bean processors that intercept bean creation.
         registerBeanPostProcessors(beanFactory); // 注册BeanPostProcessor
         beanPostProcess.end();// Bean初始化完成
         // Initialize message source for this context.
         initMessageSource();// 初始化MessageSource接口实例(资源加载)
         // Initialize event multicaster for this context.
         initApplicationEventMulticaster();// 初始化事件广播
         // Initialize other special beans in specific context subclasses.
         onRefresh();// 初始化其他特殊的操作类,方法是空的
         // Check for listener beans and register them.
         registerListeners();// 注册监听
         // Instantiate all remaining (non-lazy-init) singletons.
         finishBeanFactoryInitialization(beanFactory); // 实例化剩余的对象(非Lazy)
         // Last step: publish corresponding event.
         finishRefresh();// 相关事件发布
      } catch (BeansException ex) {
         if (logger.isWarnEnabled()) { // 日志记录
            logger.warn("Exception encountered during context initialization - " +
                  "cancelling refresh attempt: " + ex);
         }
         // Destroy already created singletons to avoid dangling resources.
         destroyBeans();// 销毁全部的bean对象
         // Reset 'active' flag.
         cancelRefresh(ex); // 设置一个存活的状态标记
         // Propagate exception to caller.
         throw ex; // 进行异常的抛出
      } finally { // 不管是否有异常都执行
         // Reset common introspection caches in Spring's core, since we
         // might not ever need metadata for singleton beans anymore...
         resetCommonCaches();// 重置缓冲
         contextRefresh.end();// 步骤的结束
      }
   }
}

StartupStep

应用启动记录

  • 容器在启动的过程之中,有可能会经历多种不同的处理步骤,同时还有可能需要记录容器启动的时长等各类信息,这些信息经过统一的收集之后,可以用于日志输出或者是发送到专属的远程服务器进行存储。

StartupStep 记录启动步骤

  • 为了更好的规划这些启动信息的记录管理,Spring 中提供了一个 StartupStep 操作接口该接口可以实现所有启动标签的记录,而要想获取此接口实例,则依靠 ApplicationStartup 接口中的 start()方法完成,图给出了一个自定义启动步骤的操作实现结构,下面将按照给出结构关联结构实现一个启动信息的完整记录。

1、
package com.yootk.main;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.metrics.ApplicationStartup;
import org.springframework.core.metrics.StartupStep;

import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.concurrent.TimeUnit;
import java.util.function.Supplier;
import java.util.stream.Collectors;

class YootkApplicationStartup implements ApplicationStartup {
    private static final Logger LOGGER = LoggerFactory.getLogger(YootkApplicationStartup.class);
    private String name;// 保存启动步骤的名称
    private long startTimestamp; // 启动步骤的触发时间戳
    private YootkStartupStep.YootkTags yootkTags = new YootkStartupStep.YootkTags();
    @Override
    public StartupStep start(String name) { // 步骤开始
        this.name = name; // 保存步骤的名称
        this.startTimestamp = System.currentTimeMillis(); // 保存步骤开始的时间戳
        LOGGER.info("【start】“{}”步骤开始执行。", this.name); // 日志的记录
        return new YootkStartupStep();
    }
    class YootkStartupStep implements StartupStep { // 定义启动步骤
        @Override
        public String getName() {
            return YootkApplicationStartup.this.name; // 启动步骤的名称
        }
        @Override
        public long getId() {
            return 3; // 定义启动步骤的ID
        }
        @Override
        public Long getParentId() {
            return null;
        }

        @Override
        public StartupStep tag(String key, String value) {
            YootkApplicationStartup.this.yootkTags.put(key, new YootkTag(key, value)); // 保存处理标签
            return this;
        }

        @Override
        public StartupStep tag(String key, Supplier<String> value) {
            YootkApplicationStartup.this.yootkTags.put(key, new YootkTag(key, value.get()));
            return this;
        }

        @Override
        public Tags getTags() {
            return YootkApplicationStartup.this.yootkTags;
        }

        @Override
        public void end() {
            LOGGER.info("【end】”{}“步骤执行完毕,所耗费的时间为:{}",
                    YootkApplicationStartup.this.name,
                    (System.currentTimeMillis() - YootkApplicationStartup.this.startTimestamp));
        }
        static class YootkTags extends LinkedHashMap<String, StartupStep.Tag>
            implements StartupStep.Tags {// 定义标签集合
            @Override
            public Iterator<Tag> iterator() {
                return this.values().stream().collect(Collectors.toList()).iterator();
            }

        }
        class YootkTag implements StartupStep.Tag {
            private String key;
            private String value;
            public YootkTag(String key, String value) {
                this.key = key;
                this.value = value;
            }
            @Override
            public String getKey() {
                return this.key;
            }

            @Override
            public String getValue() {
                return this.value;
            }
        }
    }
}
public class ApplicationStartupDemo {
    private static final Logger LOGGER = LoggerFactory.getLogger(ApplicationStartupDemo.class);
    public static void main(String[] args) throws InterruptedException {
        ApplicationStartup startup = new YootkApplicationStartup();
        StartupStep step = startup.start("yootk.application.start"); // 创建启动的步骤
        for (int x = 0; x < 3; x++) { // 循环记录
            step.tag("yootk.start.step." + x, "服务启动逻辑 - " + x);
            TimeUnit.SECONDS.sleep(1);
        }
        step.end(); // 结束当前的处理步骤
        LOGGER.info("YootkApplication启动标签:");
        for (StartupStep.Tag tag : step.getTags()) {
            LOGGER.info("【启动阶段】{} = {}", tag.getKey(), tag.getValue());
        }
    }
}

prepareRefresh()刷新预处理

1、
			// Prepare this context for refreshing.
			prepareRefresh();
2、
protected void prepareRefresh() {
   // 切换active的处理状态,同时为了更加明确的表示出当前的Spring上下文状态也提供有一个closed标记
   this.startupDate = System.currentTimeMillis();// 获取开始时间
   this.closed.set(false); // 启动的时候就需要将关闭状态设置为false
   this.active.set(true); // 启动的时候将启动的状态设置为true
   if (logger.isDebugEnabled()) { // 日志记录的处理判断
      if (logger.isTraceEnabled()) {
         logger.trace("Refreshing " + this);
      } else {
         logger.debug("Refreshing " + getDisplayName());
      }
   }
   // Initialize any placeholder property sources in the context environment.
   // 在Spring容器里面可以通过“<context>”命名空间配置所有要加载的资源信息
   initPropertySources();// PropertySources表示保存有多个属性源
   // Validate that all properties marked as required are resolvable:
   // see ConfigurablePropertyResolver#setRequiredProperties
   // 根据当前的配置环境进行一些必要的属性的验证处理
   getEnvironment().validateRequiredProperties();
   // Store pre-refresh ApplicationListeners...
   if (this.earlyApplicationListeners == null) { // 判断是否有早期的存储事件
      // 如果发现集合内容为空,则需要立即准备出一个新的集合来(集合存在了才可以保存事件的监听)
      this.earlyApplicationListeners = new LinkedHashSet<>(this.applicationListeners);
   } else { // 此时已经存在有了事件的集合处理了
      // Reset local application listeners to pre-refresh state.
      this.applicationListeners.clear();// 清空已有的事件监听集合
      this.applicationListeners.addAll(this.earlyApplicationListeners); // 保存早期事件
   }
   // Allow for the collection of early ApplicationEvents,
   // to be published once the multicaster is available...
   this.earlyApplicationEvents = new LinkedHashSet<>(); // 准备进行事件的发布处理
}
3、
/**
 * <p>Replace any stub property sources with actual instances.
 * @see org.springframework.core.env.PropertySource.StubPropertySource
 * @see org.springframework.web.context.support.
                WebApplicationContextUtils#initServletPropertySources
 */
protected void initPropertySources() {
   // For subclasses: do nothing by default.
}
4、
public ConfigurableEnvironment getEnvironment() {
   if (this.environment == null) {
      this.environment = createEnvironment();
   }
   return this.environment;
}
protected ConfigurableEnvironment createEnvironment() {
   return new StandardEnvironment();
}

obtainFreshBeanFactory()获取 BeanFactory

1、
// Tell the subclass to refresh the internal bean factory.
ConfigurableListableBeanFactory beanFactory = obtainFreshBeanFactory();


2、
protected ConfigurableListableBeanFactory obtainFreshBeanFactory() {
   refreshBeanFactory();// 刷新BeanFactory
   return getBeanFactory();// 返回BeanFactory
}


3、
@Override
public final ConfigurableListableBeanFactory getBeanFactory() {
   DefaultListableBeanFactory beanFactory = this.beanFactory; // 获取已有的BeanFactory实例
   if (beanFactory == null) { // BeanFactory为空
      throw new IllegalStateException("BeanFactory not initialized or already closed - " +
            "call 'refresh' before accessing beans via the ApplicationContext"); // 抛出异常
   }
   return beanFactory;
}


4、
protected abstract void refreshBeanFactory() throws BeansException, IllegalStateException;

5、
@Override
protected final void refreshBeanFactory() throws BeansException {
   if (hasBeanFactory()) {
      destroyBeans();
      closeBeanFactory();
   }
   try {
      DefaultListableBeanFactory beanFactory = createBeanFactory();
      beanFactory.setSerializationId(getId());
      customizeBeanFactory(beanFactory);
      loadBeanDefinitions(beanFactory);
      this.beanFactory = beanFactory;
   } catch (IOException ex) {
      throw new ApplicationContextException("I/O error parsing bean definition source for " + getDisplayName(), ex);
   }
}
protected final boolean hasBeanFactory() {
   return (this.beanFactory != null);
}
protected void destroyBeans() {
   getBeanFactory().destroySingletons();// 销毁全部的单例Bean
}
protected final void closeBeanFactory() {
   DefaultListableBeanFactory beanFactory = this.beanFactory;
   if (beanFactory != null) {
      beanFactory.setSerializationId(null);  // 取消掉ID 的配置
      this.beanFactory = null; // 清空对象引用
   }
}


6、
protected void loadBeanDefinitions(DefaultListableBeanFactory beanFactory) throws BeansException, IOException {
   // Create a new XmlBeanDefinitionReader for the given BeanFactory.
   // 创建一个XML风格的Bean定义信息的读取类
   XmlBeanDefinitionReader beanDefinitionReader = new XmlBeanDefinitionReader(beanFactory);
   // Configure the bean definition reader with this context's resource loading environment.
   beanDefinitionReader.setEnvironment(this.getEnvironment());// 环境配置
   beanDefinitionReader.setResourceLoader(this); // 设置ResourceLoader
   beanDefinitionReader.setEntityResolver(new ResourceEntityResolver(this)); // 实体解析器
   // Allow a subclass to provide custom initialization of the reader,
   // then proceed with actually loading the bean definitions.
   initBeanDefinitionReader(beanDefinitionReader); // 读取初始化
   loadBeanDefinitions(beanDefinitionReader); // 数据读取
}

prepareBeanFactory()预处理 BeanFactory

1、
// Prepare the bean factory for use in this context.
prepareBeanFactory(beanFactory);


2、
protected void prepareBeanFactory(ConfigurableListableBeanFactory beanFactory) {
   // Tell the internal bean factory to use the context's class loader etc.
   beanFactory.setBeanClassLoader(getClassLoader());// 配置一个类加载器
   if (!shouldIgnoreSpel) { // 是否要忽略SpEL处理
      beanFactory.setBeanExpressionResolver(// 设置表达式解析处理类
            new StandardBeanExpressionResolver(beanFactory.getBeanClassLoader()));
   }
   beanFactory.addPropertyEditorRegistrar(
            new ResourceEditorRegistrar(this, getEnvironment()));// 添加属性编辑器的注册管理
   // Configure the bean factory with context callbacks.
   // Spring容器内部存在有各类的Callback支持(回调处理)
   // 在BeanFactory准备完成之后,需要配置有各个的Aware接口处理类,实现各类核心资源的注入
   beanFactory.addBeanPostProcessor(new ApplicationContextAwareProcessor(this));
   beanFactory.ignoreDependencyInterface(EnvironmentAware.class);
   beanFactory.ignoreDependencyInterface(EmbeddedValueResolverAware.class);
   beanFactory.ignoreDependencyInterface(ResourceLoaderAware.class);
   beanFactory.ignoreDependencyInterface(ApplicationEventPublisherAware.class);
   beanFactory.ignoreDependencyInterface(MessageSourceAware.class);
   beanFactory.ignoreDependencyInterface(ApplicationContextAware.class);
   beanFactory.ignoreDependencyInterface(ApplicationStartupAware.class);
   // BeanFactory interface not registered as resolvable type in a plain factory.
   // MessageSource registered (and found for autowiring) as a bean.
// 设置依赖解析处理之中所有核心的结构
   beanFactory.registerResolvableDependency(BeanFactory.class, beanFactory);
   beanFactory.registerResolvableDependency(ResourceLoader.class, this);
   beanFactory.registerResolvableDependency(ApplicationEventPublisher.class, this);
   beanFactory.registerResolvableDependency(ApplicationContext.class, this);
   // Register early post-processor for detecting inner beans as ApplicationListeners.
   beanFactory.addBeanPostProcessor(new ApplicationListenerDetector(this)); // 早期监听
   // Detect a LoadTimeWeaver and prepare for weaving, if found.
   if (!NativeDetector.inNativeImage() &&
           beanFactory.containsBean(LOAD_TIME_WEAVER_BEAN_NAME)) { // LTW技术
      beanFactory.addBeanPostProcessor(new LoadTimeWeaverAwareProcessor(beanFactory));
      // Set a temporary ClassLoader for type matching.
      beanFactory.setTempClassLoader(new ContextTypeMatchClassLoader(
             beanFactory.getBeanClassLoader()));
   }
   // Register default environment beans.
   // 注册默认的环境配置Bean
   if (!beanFactory.containsLocalBean(ENVIRONMENT_BEAN_NAME)) { // 是否有指定的内容
      beanFactory.registerSingleton(ENVIRONMENT_BEAN_NAME, getEnvironment());// 注册
   }
   if (!beanFactory.containsLocalBean(SYSTEM_PROPERTIES_BEAN_NAME)) { // 是否有指定的内容
      beanFactory.registerSingleton(SYSTEM_PROPERTIES_BEAN_NAME,
            getEnvironment().getSystemProperties());// 注册
   }
   if (!beanFactory.containsLocalBean(SYSTEM_ENVIRONMENT_BEAN_NAME)) {
      beanFactory.registerSingleton(SYSTEM_ENVIRONMENT_BEAN_NAME,
          getEnvironment().getSystemEnvironment());
   }
   if (!beanFactory.containsLocalBean(APPLICATION_STARTUP_BEAN_NAME)) {
      beanFactory.registerSingleton(APPLICATION_STARTUP_BEAN_NAME, getApplicationStartup());
   }
}

initMessageSource()初始化消息资源

1、
protected void initMessageSource() {
   ConfigurableListableBeanFactory beanFactory = getBeanFactory();// 获取BeanFactory
   // 在当前的BeanFactory内部是否已经提供有指定名称的对象实例
   if (beanFactory.containsLocalBean(MESSAGE_SOURCE_BEAN_NAME)) { // 实例存在判断
      // 获取指定的Bean对象实例
      this.messageSource = beanFactory.getBean(MESSAGE_SOURCE_BEAN_NAME, MessageSource.class);
      // Make MessageSource aware of parent MessageSource.
      if (this.parent != null && this.messageSource instanceof HierarchicalMessageSource hms) {
         if (hms.getParentMessageSource() == null) {
            // Only set parent context as parent MessageSource if no parent MessageSource
            // registered already.
            hms.setParentMessageSource(getInternalParentMessageSource());
         }
      }
      if (logger.isTraceEnabled()) {
         logger.trace("Using MessageSource [" + this.messageSource + "]");
      }
   } else { // 没有指定的Bean实例
      // Use empty MessageSource to be able to accept getMessage calls.
      DelegatingMessageSource dms = new DelegatingMessageSource();// 实例化新对象
      dms.setParentMessageSource(getInternalParentMessageSource());// 父资源的配置
      this.messageSource = dms;
      beanFactory.registerSingleton(MESSAGE_SOURCE_BEAN_NAME, this.messageSource); // Bean注册
      if (logger.isTraceEnabled()) {
         logger.trace("No '" + MESSAGE_SOURCE_BEAN_NAME + "' bean, using [" +
                     this.messageSource + "]");
      }
   }
}

initApplicationEventMulticaster()初始化事件广播

1、
protected void initApplicationEventMulticaster() {
   ConfigurableListableBeanFactory beanFactory = getBeanFactory();// 获取BeanFactory获取
   // 在Spring的内部会保存有大量的系统实例,那么这个时候就是进行 Bean是否存在的判断
   if (beanFactory.containsLocalBean(APPLICATION_EVENT_MULTICASTER_BEAN_NAME)) {
      this.applicationEventMulticaster =
            beanFactory.getBean(APPLICATION_EVENT_MULTICASTER_BEAN_NAME,
                       ApplicationEventMulticaster.class); // 获取Bean实例
      if (logger.isTraceEnabled()) { // 日志记录
         logger.trace("Using ApplicationEventMulticaster [" +
                     this.applicationEventMulticaster + "]");
      }
   } else { // 如果现在没有指定的Bean实例
      this.applicationEventMulticaster = new SimpleApplicationEventMulticaster(beanFactory);
      beanFactory.registerSingleton(APPLICATION_EVENT_MULTICASTER_BEAN_NAME,
            this.applicationEventMulticaster);
      if (logger.isTraceEnabled()) {
         logger.trace("No '" + APPLICATION_EVENT_MULTICASTER_BEAN_NAME + "' bean, using " +
               "[" + this.applicationEventMulticaster.getClass().getSimpleName() + "]");
      }
   }
}

registerListeners()注册事件监听器

1、
private final Set<ApplicationListener<?>> applicationListeners = new LinkedHashSet<>();
public Collection<ApplicationListener<?>> getApplicationListeners() {
   return this.applicationListeners;
}
public void addApplicationListener(ApplicationListener<?> listener) {
   Assert.notNull(listener, "ApplicationListener must not be null");
   if (this.applicationEventMulticaster != null) {
      this.applicationEventMulticaster.addApplicationListener(listener);
   }
   this.applicationListeners.add(listener);
}


2、
protected void registerListeners() {
   // Register statically specified listeners first.
   // 获取Spring容器启动时所添加的全部的事件监听类的集合
   for (ApplicationListener<?> listener : getApplicationListeners()) { // 获取全部监听器
      // 在之前调用了“initApplicationEventMulticaster()”处理方法
      getApplicationEventMulticaster().addApplicationListener(listener); //
   }
   // Do not initialize FactoryBeans here: We need to leave all regular beans
   // uninitialized to let post-processors apply to them!
   // 获取当前 Spring上下文之中所有指定类型的Bean名称实例
   String[] listenerBeanNames = getBeanNamesForType(ApplicationListener.class, true, false);
   for (String listenerBeanName : listenerBeanNames) { // Bean名称迭代
      // 将当前获取到的Bean名称,加入到当前的广播管理之中(以便于广播消息时,可以收到事件信息)
      getApplicationEventMulticaster().addApplicationListenerBean(listenerBeanName);
   }
   // Publish early application events now that we finally have a multicaster...
   // 有可能在Spring容器(Spring上下文)没有初始化完成时就已经保存了一些事件,获取这些事件信息
   Set<ApplicationEvent> earlyEventsToProcess = this.earlyApplicationEvents;
   this.earlyApplicationEvents = null; // 清空早期的事件
   if (!CollectionUtils.isEmpty(earlyEventsToProcess)) { // 当前存在有事件处理的集合项
      for (ApplicationEvent earlyEvent : earlyEventsToProcess) { // 获取事件类型
         getApplicationEventMulticaster().multicastEvent(earlyEvent); // 广播时依据事件类型处理
      }
   }
}

finishBeanFactorylnitialization()初始化完成

1、
protected void finishBeanFactoryInitialization(ConfigurableListableBeanFactory beanFactory) {
   // Initialize conversion service for this context.
   // 初始化ConversionServie服务处理(可以实现数据转型的服务支持),所有通过配置文件注册的属性
   if (beanFactory.containsBean(CONVERSION_SERVICE_BEAN_NAME) &&
         beanFactory.isTypeMatch(CONVERSION_SERVICE_BEAN_NAME, ConversionService.class)) {
      beanFactory.setConversionService(// 进行Bean实例获取
            beanFactory.getBean(CONVERSION_SERVICE_BEAN_NAME, ConversionService.class));
   }
   // Register a default embedded value resolver if no BeanFactoryPostProcessor
   // (such as a PropertySourcesPlaceholderConfigurer bean) registered any before:
   // at this point, primarily for resolution in annotation attribute values.
   if (!beanFactory.hasEmbeddedValueResolver()) { // 是否包含有内嵌的数据解析器
      beanFactory.addEmbeddedValueResolver(strVal ->
		getEnvironment().resolvePlaceholders(strVal)); // 进行解析器的注册
   }
   // Initialize LoadTimeWeaverAware beans early to allow for registering their transformers early.
   // 在进行Java动态代理织入的时候一般会考虑到LTW的设计问题,那么此时解决的就是LTW的注册
   String[] weaverAwareNames = beanFactory.getBeanNamesForType(
                    LoadTimeWeaverAware.class, false, false);
   for (String weaverAwareName : weaverAwareNames) {
      getBean(weaverAwareName); // 获取Bean
   }
   // Stop using the temporary ClassLoader for type matching.
   beanFactory.setTempClassLoader(null); // 清除临时的类加载器
   // Allow for caching all bean definition metadata, not expecting further changes.
   beanFactory.freezeConfiguration();// 缓存所有的Bean定义信息
   // Instantiate all remaining (non-lazy-init) singletons.
   beanFactory.preInstantiateSingletons();// 实例化剩余的单例Bean。
}

2、
@Override
public void preInstantiateSingletons() throws BeansException {
   if (logger.isTraceEnabled()) {  // 日志记录处理
      logger.trace("Pre-instantiating singletons in " + this);
   }
   // Iterate over a copy to allow for init methods which in turn register new bean definitions.
   // While this may not be part of the regular factory bootstrap, it does otherwise work fine.
   List<String> beanNames = new ArrayList<>(this.beanDefinitionNames); // 获取Bean名称
   // Trigger initialization of all non-lazy singleton beans...
   for (String beanName : beanNames) {  // Bean名称迭代
      RootBeanDefinition bd = getMergedLocalBeanDefinition(beanName); // 获取Bean定义
      if (!bd.isAbstract() && bd.isSingleton() && !bd.isLazyInit()) {  // 各种判断
         if (isFactoryBean(beanName)) {  // 是否为FactoryBean
            Object bean = getBean(FACTORY_BEAN_PREFIX + beanName);
            if (bean instanceof SmartFactoryBean<?> smartFactoryBean &&
                          smartFactoryBean.isEagerInit()) { // 是否为FactoryBean实例处理
               getBean(beanName); // 获取Bean
            }
         } else {
            getBean(beanName); // 直接获取Bean
         }
      }
   }
   // Trigger post-initialization callback for all applicable beans...
   for (String beanName : beanNames) { // CallBack处理
      Object singletonInstance = getSingleton(beanName); // 获取单例Bean信息
      if (singletonInstance instanceof SmartInitializingSingleton smartSingleton) {
         StartupStep smartInitialize = this.getApplicationStartup().start("spring.beans.smart-initialize")
               .tag("beanName", beanName); // 配置启动步骤
         smartSingleton.afterSingletonsInstantiated();// SmartInitializingSingleton初始化完成
         smartInitialize.end();
      }
   }
}

3、
protected void initLifecycleProcessor() {
   ConfigurableListableBeanFactory beanFactory = getBeanFactory();// 获取BeanFactory
   if (beanFactory.containsLocalBean(LIFECYCLE_PROCESSOR_BEAN_NAME)) {
      // 获取所有的LifecycleProcessor接口实例
      this.lifecycleProcessor =
            beanFactory.getBean(LIFECYCLE_PROCESSOR_BEAN_NAME, LifecycleProcessor.class);
      if (logger.isTraceEnabled()) {
         logger.trace("Using LifecycleProcessor [" + this.lifecycleProcessor + "]");
      }
   } else { // 如果没有发现指定的Bean存在
      DefaultLifecycleProcessor defaultProcessor = new DefaultLifecycleProcessor();
      defaultProcessor.setBeanFactory(beanFactory); // 设置BeanFactory
      this.lifecycleProcessor = defaultProcessor;
      beanFactory.registerSingleton(LIFECYCLE_PROCESSOR_BEAN_NAME, this.lifecycleProcessor);
      if (logger.isTraceEnabled()) {
         logger.trace("No '" + LIFECYCLE_PROCESSOR_BEAN_NAME + "' bean, using " +
               "[" + this.lifecycleProcessor.getClass().getSimpleName() + "]");
      }
   }
}

4、
private void startBeans(boolean autoStartupOnly) { // Bean开始处理
   Map<String, Lifecycle> lifecycleBeans = getLifecycleBeans();
   Map<Integer, LifecycleGroup> phases = new TreeMap<>();
   lifecycleBeans.forEach((beanName, bean) -> {
      if (!autoStartupOnly || (bean instanceof SmartLifecycle &&
                 ((SmartLifecycle) bean).isAutoStartup())) {
         int phase = getPhase(bean); // Bean的处理阶段
         phases.computeIfAbsent(
               phase,
               p -> new LifecycleGroup(phase, this.timeoutPerShutdownPhase,
                          lifecycleBeans, autoStartupOnly) // 添加生命周期管理组
         ).add(beanName, bean);
      }
   });
   if (!phases.isEmpty()) { // 阶段不为空
      phases.values().forEach(LifecycleGroup::start); // 开始执行初始化调用
   }
}

AnnotationConfigApplicationContext 核心结构

1、
public class AnnotationConfigApplicationContext extends
GenericApplicationContext implements AnnotationConfigRegistry {}
public class GenericApplicationContext extends
AbstractApplicationContext implements BeanDefinitionRegistry {}


2、
public AnnotationConfigApplicationContext() {
   StartupStep createAnnotatedBeanDefReader = this.getApplicationStartup()
          .start("spring.context.annotated-bean-reader.create");
   this.reader = new AnnotatedBeanDefinitionReader(this); // 注解配置类的读取
   createAnnotatedBeanDefReader.end();
   this.scanner = new ClassPathBeanDefinitionScanner(this); // ClassPath中Bean定义扫描处理
}
public AnnotationConfigApplicationContext(Class<?>... componentClasses) { // 组件类
   this(); // 无参构造
   register(componentClasses);
   refresh();
}
public AnnotationConfigApplicationContext(String... basePackages) { // 扫描包
   this(); // 无参构造
   scan(basePackages);
   refresh();
}


3、
public void register(Class<?>... componentClasses) {
   Assert.notEmpty(componentClasses, "At least one component class must be specified");
   StartupStep registerComponentClass = this.getApplicationStartup().start("spring.context.component-classes.register")
         .tag("classes", () -> Arrays.toString(componentClasses));
   this.reader.register(componentClasses);
   registerComponentClass.end();
}


4、
public void scan(String... basePackages) {
   Assert.notEmpty(basePackages, "At least one base package must be specified");
   StartupStep scanPackages = this.getApplicationStartup().start("spring.context.base-packages.scan")
         .tag("packages", () -> Arrays.toString(basePackages));
   this.scanner.scan(basePackages);
   scanPackages.end();
}

ClassPathBeanDefinitionScanner 扫描处理

1、
protected Set<BeanDefinitionHolder> doScan(String... basePackages) {
   Assert.notEmpty(basePackages, "At least one base package must be specified"); // 断言
   Set<BeanDefinitionHolder> beanDefinitions = new LinkedHashSet<>(); // Bean定义处理
   for (String basePackage : basePackages) { // 扫描包配置
      Set<BeanDefinition> candidates = findCandidateComponents(basePackage);
      for (BeanDefinition candidate : candidates) { // 获取每一个Bean的定义对象实例
         ScopeMetadata scopeMetadata =
              this.scopeMetadataResolver.resolveScopeMetadata(candidate); // 解析Scope元数据
         candidate.setScope(scopeMetadata.getScopeName());// 设置Scope信息
         // 通过注解的方式定义的Bean是没有名称的,这个名称可能是类名称,也有可能是方法名称
         String beanName = this.beanNameGenerator.generateBeanName(candidate, this.registry);
         if (candidate instanceof AbstractBeanDefinition) { // 类型的判断
            postProcessBeanDefinition((AbstractBeanDefinition) candidate, beanName); // 处理
         }
         if (candidate instanceof AnnotatedBeanDefinition) { // 通过注解定义
            AnnotationConfigUtils.processCommonDefinitionAnnotations(
(AnnotatedBeanDefinition) candidate); // Bean处理
         }
         if (checkCandidate(beanName, candidate)) {
            BeanDefinitionHolder definitionHolder =
new BeanDefinitionHolder(candidate, beanName); // Bean定义的控制器
            definitionHolder =
                  AnnotationConfigUtils.applyScopedProxyMode(
scopeMetadata, definitionHolder, this.registry); // 设置代理模式
            beanDefinitions.add(definitionHolder); // 保存实例
            registerBeanDefinition(definitionHolder, this.registry); // 注册处理
         }
      }
   }
   return beanDefinitions;
}


2、
public String generateBeanName(BeanDefinition definition, BeanDefinitionRegistry registry) {
   if (definition instanceof AnnotatedBeanDefinition) {
      String beanName = determineBeanNameFromAnnotation((AnnotatedBeanDefinition) definition);
      if (StringUtils.hasText(beanName)) { // 已经存在有了Bean名称
         // Explicit bean name found.
         return beanName; // 返回Bean名称定义
      }
   }
   // Fallback: generate a unique default bean name.
   return buildDefaultBeanName(definition, registry); // 生成Bean名称
}

protected String buildDefaultBeanName(BeanDefinition definition) {
   String beanClassName = definition.getBeanClassName();
   Assert.state(beanClassName != null, "No bean class name set");
   String shortClassName = ClassUtils.getShortName(beanClassName);
   return Introspector.decapitalize(shortClassName);
}


3、
private Set<BeanDefinition> scanCandidateComponents(String basePackage) {
   Set<BeanDefinition> candidates = new LinkedHashSet<>();
   try {
      String packageSearchPath = ResourcePatternResolver.CLASSPATH_ALL_URL_PREFIX +
            resolveBasePackage(basePackage) + '/' + this.resourcePattern; // 资源定位
      // Resource表示的是资源数组,所以此时是通过特定的方式实现了配置资源的加载
      Resource[] resources = getResourcePatternResolver().getResources(packageSearchPath);
      boolean traceEnabled = logger.isTraceEnabled();// 日志记录的要求
      boolean debugEnabled = logger.isDebugEnabled();// 日志记录的要求
      for (Resource resource : resources) { // 资源迭代
         if (traceEnabled) { // 日志输出
            logger.trace("Scanning " + resource);
         }
         try { // 资源可能来自于 jar文件也有可能来自于文件
            MetadataReader metadataReader =
getMetadataReaderFactory().getMetadataReader(resource); // 获取资源元数据
            if (isCandidateComponent(metadataReader)) { // 是否为候选组件(是否等待注册)
               ScannedGenericBeanDefinition sbd =
new ScannedGenericBeanDefinition(metadataReader); // 扫描注册定义
               sbd.setSource(resource); // 设置资源信息
               if (isCandidateComponent(sbd)) {
                  if (debugEnabled) {
                     logger.debug("Identified candidate component class: " + resource);
                  }
                  candidates.add(sbd); // 加入后续注册Bean实例
               } else {
                  if (debugEnabled) {
                     logger.debug("Ignored because not a concrete top-level class: " + resource);
                  }
               }
            } else {
               if (traceEnabled) {
                  logger.trace("Ignored because not matching any filter: " + resource);
               }
            }
         } catch (FileNotFoundException ex) {
            if (traceEnabled) {
               logger.trace("Ignored non-readable " + resource + ": " + ex.getMessage());
            }
         } catch (Throwable ex) {
            throw new BeanDefinitionStoreException(
                  "Failed to read candidate component class: " + resource, ex);
         }
      }
   } catch (IOException ex) {
      throw new BeanDefinitionStoreException("I/O failure during classpath scanning", ex);
   }
   return candidates;
}


4、
static void processCommonDefinitionAnnotations(AnnotatedBeanDefinition abd, AnnotatedTypeMetadata metadata) {
   AnnotationAttributes lazy = attributesFor(metadata, Lazy.class);
   if (lazy != null) {
      abd.setLazyInit(lazy.getBoolean("value"));
   } lse if (abd.getMetadata() != metadata) {
      lazy = attributesFor(abd.getMetadata(), Lazy.class);
      if (lazy != null) {
         abd.setLazyInit(lazy.getBoolean("value"));
      }
   }
   if (metadata.isAnnotated(Primary.class.getName())) {
      abd.setPrimary(true);
   }
   AnnotationAttributes dependsOn = attributesFor(metadata, DependsOn.class);
   if (dependsOn != null) {
      abd.setDependsOn(dependsOn.getStringArray("value"));
   }
   AnnotationAttributes role = attributesFor(metadata, Role.class);
   if (role != null) {
      abd.setRole(role.getNumber("value").intValue());
   }
   AnnotationAttributes description = attributesFor(metadata, Description.class);
   if (description != null) {
      abd.setDescription(description.getString("value"));
   }
}


5、
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); // 别名注册
      }
   }
}

AnnotatedBeanDefinitionReader 配置类处理

1、
private <T> void doRegisterBean(Class<T> beanClass, @Nullable String name,
      @Nullable Class<? extends Annotation>[] qualifiers, @Nullable Supplier<T> supplier,
      @Nullable BeanDefinitionCustomizer[] customizers) {
   // 创建一个BeanDefition子类实例(Spring里面如果要找到了BeanDefitinon实例就表示注册成功)
   AnnotatedGenericBeanDefinition abd = new AnnotatedGenericBeanDefinition(beanClass);
   if (this.conditionEvaluator.shouldSkip(abd.getMetadata())) { // 跳过此类配置
      return; // 结束了
   }
   abd.setInstanceSupplier(supplier); // 实例供给操作
   // 要解析当前 Bean之中提供的Scope元数据信息
   ScopeMetadata scopeMetadata = this.scopeMetadataResolver.resolveScopeMetadata(abd);
   abd.setScope(scopeMetadata.getScopeName());// 保存在BeanDefition接口实例之中
   String beanName = (name != null ? name : this.beanNameGenerator.generateBeanName(abd, this.registry)); // 生成Bean名称
   AnnotationConfigUtils.processCommonDefinitionAnnotations(abd); // 注册处理
   if (qualifiers != null) {
      for (Class<? extends Annotation> qualifier : qualifiers) {
         if (Primary.class == qualifier) { // 注解的处理
            abd.setPrimary(true);
         } else if (Lazy.class == qualifier) { // 注解处理
            abd.setLazyInit(true);
         } else {
            abd.addQualifier(new AutowireCandidateQualifier(qualifier));
         }
      }
   }
   if (customizers != null) {
      for (BeanDefinitionCustomizer customizer : customizers) {
         customizer.customize(abd); // Bean自定义的信息
      }
   }
   // 将当前的Bean名称、BeanDefition接口实例保存在beanDefitionHolder对象之中(承载器)
   BeanDefinitionHolder definitionHolder = new BeanDefinitionHolder(abd, beanName);
   definitionHolder = AnnotationConfigUtils.applyScopedProxyMode(scopeMetadata, definitionHolder, this.registry);
   BeanDefinitionReaderUtils.registerBeanDefinition(definitionHolder, this.registry);
}

BeanDefinitionReaderUtils 工具类

1、
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);
      }
   }
}


2、
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 abd) { // 判断类型是否满足要求
      try {
         abd.validate(); // 验证
      } catch (BeanDefinitionValidationException ex) { … }
   }
   // BeanFactory的内部已经存在有了大量的BeanDefinition定义,而这些定义保存在Map集合之中
   BeanDefinition existingDefinition = this.beanDefinitionMap.get(beanName); // 获取已存在Bean
   if (existingDefinition != null) { // Bean不为空
      if (!isAllowBeanDefinitionOverriding()) { // 是否允许覆盖
         throw new BeanDefinitionOverrideException(beanName, beanDefinition, existingDefinition); // 不允许覆盖,直接抛出异常
      } else if (existingDefinition.getRole() < beanDefinition.getRole()) {  // 角色的判断
         // e.g. was ROLE_APPLICATION, now overriding with ROLE_SUPPORT or ROLE_INFRASTRUCTURE
         if (logger.isInfoEnabled()) {
            logger.info("Overriding user-defined bean definition for bean '" + beanName +
                  "' with a framework-generated bean definition: replacing [" +
                  existingDefinition + "] with [" + beanDefinition + "]");
         }
      } else if (!beanDefinition.equals(existingDefinition)) {  // Bean相同判断
         if (logger.isDebugEnabled()) {
            logger.debug("Overriding bean definition for bean '" + beanName +
                  "' with a different definition: replacing [" + existingDefinition +
                  "] with [" + beanDefinition + "]");
         }
      } else {
         if (logger.isTraceEnabled()) {
            logger.trace("Overriding bean definition for bean '" + beanName +
                  "' with an equivalent definition: replacing [" + existingDefinition +
                  "] with [" + beanDefinition + "]");
         }
      }
      this.beanDefinitionMap.put(beanName, beanDefinition); // 如果没问题则保存BeanDefition定义
   } else {  // 别名的判断了
      if (isAlias(beanName)) {
         if (!isAllowBeanDefinitionOverriding()) {
            String aliasedName = canonicalName(beanName);
            if (containsBeanDefinition(aliasedName)) {  // alias for existing bean definition
               throw new BeanDefinitionOverrideException(
                     beanName, beanDefinition, getBeanDefinition(aliasedName));
            } else {  // alias pointing to non-existing bean definition
               throw new BeanDefinitionStoreException(
beanDefinition.getResourceDescription(), beanName,
                     "Cannot register bean definition for bean '" + beanName +
                     "' since there is already an alias for bean '" + aliasedName + "' bound.");
            }
         } else {
            removeAlias(beanName);
         }
      }
      if (hasBeanCreationStarted()) {
         // Cannot modify startup-time collection elements anymore (for stable iteration)
         synchronized (this.beanDefinitionMap) {  // Map集合的修改需要同步
            this.beanDefinitionMap.put(beanName, beanDefinition);
            List<String> updatedDefinitions = new ArrayList<>(
this.beanDefinitionNames.size() + 1);
            updatedDefinitions.addAll(this.beanDefinitionNames);
            updatedDefinitions.add(beanName);
            this.beanDefinitionNames = updatedDefinitions;
            removeManualSingletonName(beanName);
         }
      } else {
         // Still in startup registration phase
         this.beanDefinitionMap.put(beanName, beanDefinition);
         this.beanDefinitionNames.add(beanName);
         removeManualSingletonName(beanName);
      }
      this.frozenBeanDefinitionNames = null;
   }
   if (existingDefinition != null || containsSingleton(beanName)) {
      resetBeanDefinition(beanName);
   } else if (isConfigurationFrozen()) {
      clearByTypeCache();
   }
}

demo


上次编辑于: