Spring IoC 容器大概流程

   很早就看过spring IoC容器源码,一直没时间做系统的整理,现在大概整理下:

核心类关系: 
    ClassPathXmlApplicationContext extends AbstractXmlApplicationContext
    AbstractXmlApplicationContext extends AbstractRefreshableConfigApplicationContext
    AbstractRefreshableConfigApplicationContext extends AbstractRefreshableApplicationContext
    AbstractRefreshableApplicationContext extends AbstractApplicationContext
    AbstractApplicationContext extends DefaultResourceLoader
    DefaultResourceLoader implements ResourceLoader
    
    private DefaultListableBeanFactory AbstractRefreshableApplicationContext.beanFactory;

大概流程:

  //ClassPathXmlApplicationContext 构造
    public ClassPathXmlApplicationContext(String[] configLocations, boolean refresh, ApplicationContext parent) throws BeansException {
           super(parent);
           //对configLocations 加载路径的处理 调用了 AbstractRefreshableConfigApplicationContext.setConfigLocations
           this.setConfigLocations(configLocations);
           if (refresh) {
               //这是核心 刷新context 调用了AbstractApplicationContext.refresh  
               this.refresh();
           }
  
      }
      //AbstractRefreshableConfigApplicationContext.setConfigLocations
      public void setConfigLocations(String[] locations) {
          if (locations != null) {
              Assert.noNullElements(locations, "Config locations must not be null");
              this.configLocations = new String[locations.length];
  
              for(int i = 0; i < locations.length; ++i) {
                  //这里解析路径 替换占位符
                 this.configLocations[i] = this.resolvePath(locations[i]).trim();
              }
          } else {
              this.configLocations = null;
          }
      }
      //AbstractRefreshableConfigApplicationContext.resolvePath
      protected String resolvePath(String path) {
          return SystemPropertyUtils.resolvePlaceholders(path);
      }
      
      //AbstractApplicationContext.refresh  
      public void refresh() throws BeansException, IllegalStateException {
          synchronized(this.startupShutdownMonitor) {
              //准备刷新  这里记录了startupDate=now  active=true 两个变量
              this.prepareRefresh();
              //获取 BeanFactory 及bean的定义
              ConfigurableListableBeanFactory beanFactory = this.obtainFreshBeanFactory();
              //初始化 BeanFactory 设定一些参数
              this.prepareBeanFactory(beanFactory);
  
              try {
                  //如果有需要-留给子类实现的空方法
                  this.postProcessBeanFactory(beanFactory);
                  //执行 BeanFactoryPostProcessor 相关bean
                  this.invokeBeanFactoryPostProcessors(beanFactory);
                  //从bean工厂中找到实现了BeanPostProcessor的bean实例化并注册BeanPostProcessor 
                  this.registerBeanPostProcessors(beanFactory);
                  //初始化 MessageSource 自定义可用messageSource作为beanName
                  this.initMessageSource();
                  //初始化ApplicationEventMulticaster事件广播器 
                  //自定义可用applicationEventMulticaster作为beanName
                  this.initApplicationEventMulticaster();
                  //如果有需要-留给子类实现的空方法
                  this.onRefresh();
                  //注册 ApplicationListener
                  this.registerListeners();
                  //加载所有剩余的(非延迟)单例Bean
                  this.finishBeanFactoryInitialization(beanFactory);
                  //发布事件 
                  this.finishRefresh();
              } catch (BeansException var4) {
                  this.destroyBeans();
                  this.cancelRefresh(var4);
                  throw var4;
              }
  
          }
      }
      
      //AbstractApplicationContext.obtainFreshBeanFactory
      protected ConfigurableListableBeanFactory obtainFreshBeanFactory() {
          //刷新BeanFactory  主要作用是销毁原来的 BeanFactory 并创建新的
          this.refreshBeanFactory();
          //从this.beanFactory获取当前BeanFactory
          ConfigurableListableBeanFactory beanFactory = this.getBeanFactory();
          if (this.logger.isDebugEnabled()) {
              this.logger.debug("Bean factory for " + this.getDisplayName() + ": " + beanFactory);
          }
  
          return beanFactory;
      }
      
      //AbstractRefreshableApplicationContext.refreshBeanFactory
      protected final void refreshBeanFactory() throws BeansException {
          if (this.hasBeanFactory()) { /
              this.destroyBeans();
              this.closeBeanFactory();
          }
  
          try {
              //创建新的beanFactory
              DefaultListableBeanFactory beanFactory = this.createBeanFactory();
              beanFactory.setSerializationId(this.getId());
              this.customizeBeanFactory(beanFactory);
              //从xml加载bean定义
              this.loadBeanDefinitions(beanFactory);
              synchronized(this.beanFactoryMonitor) {
                  this.beanFactory = beanFactory;
              }
          } catch (IOException var4) {
             throw new ApplicationContextException("I/O error parsing bean definition source for " + this.getDisplayName(), var4);
         }
     }
     
     //AbstractApplicationContext.finishRefresh
     protected void finishRefresh() {
         //初始化 lifecycleProcessor
         initLifecycleProcessor();
 
         //lifecycleProcessor.onRefresh
         getLifecycleProcessor().onRefresh();
 
         //发布ApplicationContext刷新事件
         publishEvent(new ContextRefreshedEvent(this));
     }
     
     //AbstractApplicationContext.initApplicationEventMulticaster
     //APPLICATION_EVENT_MULTICASTER_BEAN_NAME="applicationEventMulticaster"
     protected void initApplicationEventMulticaster() {
         ConfigurableListableBeanFactory beanFactory = getBeanFactory();
         //给自定义ApplicationEventMulticaster留的位置  APPLICATION_EVENT_MULTICASTER_BEAN_NAME
         if (beanFactory.containsLocalBean(APPLICATION_EVENT_MULTICASTER_BEAN_NAME)) {
             this.applicationEventMulticaster =
                     beanFactory.getBean(APPLICATION_EVENT_MULTICASTER_BEAN_NAME, ApplicationEventMulticaster.class);
             if (logger.isDebugEnabled()) {
                 logger.debug("Using ApplicationEventMulticaster [" + this.applicationEventMulticaster + "]");
             }
         }
         else {
             this.applicationEventMulticaster = new SimpleApplicationEventMulticaster(beanFactory);
             beanFactory.registerSingleton(APPLICATION_EVENT_MULTICASTER_BEAN_NAME, this.applicationEventMulticaster);
             if (logger.isDebugEnabled()) {
                 logger.debug("Unable to locate ApplicationEventMulticaster with name '" +
                         APPLICATION_EVENT_MULTICASTER_BEAN_NAME +
                         "': using default [" + this.applicationEventMulticaster + "]");
             }
         }
     }
     
     //AbstractApplicationContext.finishRefresh
     protected void finishRefresh() {
         // 初始化Context生命周期 Processer
         initLifecycleProcessor();
 
         
         getLifecycleProcessor().onRefresh();
 
         //推送
         publishEvent(new ContextRefreshedEvent(this));
     }
     
     //AbstractApplicationContext.initLifecycleProcessor
     //LIFECYCLE_PROCESSOR_BEAN_NAME="lifecycleProcessor"
     protected void initLifecycleProcessor() {
         //初始化Context生命周期 bean  
         ConfigurableListableBeanFactory beanFactory = getBeanFactory();
         //给LifecycleProcessor留的位置LIFECYCLE_PROCESSOR_BEAN_NAME
         if (beanFactory.containsLocalBean(LIFECYCLE_PROCESSOR_BEAN_NAME)) {
             this.lifecycleProcessor =
                     beanFactory.getBean(LIFECYCLE_PROCESSOR_BEAN_NAME, LifecycleProcessor.class);
             if (logger.isDebugEnabled()) {
                 logger.debug("Using LifecycleProcessor [" + this.lifecycleProcessor + "]");
             }
         }
         else {
             DefaultLifecycleProcessor defaultProcessor = new DefaultLifecycleProcessor();
             defaultProcessor.setBeanFactory(beanFactory);
             this.lifecycleProcessor = defaultProcessor;
             beanFactory.registerSingleton(LIFECYCLE_PROCESSOR_BEAN_NAME, this.lifecycleProcessor);
             if (logger.isDebugEnabled()) {
                 logger.debug("Unable to locate LifecycleProcessor with name '" +
                         LIFECYCLE_PROCESSOR_BEAN_NAME +
                         "': using default [" + this.lifecycleProcessor + "]");
             }
         }
     }
原文地址:https://www.cnblogs.com/dint/p/14117236.html