spring-BeanFactory源码解析

找入口

// Tell the subclass to refresh the internal bean factory.
// STEP 2:
//      a) 创建IoC容器(DefaultListableBeanFactory)
//      b) 加载解析XML文件(最终存储到Document对象中)
//      c) 读取Document对象,并完成BeanDefinition的加载和注册工作
ConfigurableListableBeanFactory beanFactory = obtainFreshBeanFactory();

流程解析

  • 进入AbstractApplicationobtainFreshBeanFactory方法:

    用于创建一个新的IoC容器,这个IoC容器就是DefaultListableBeanFactory对象。

 protected ConfigurableListableBeanFactory obtainFreshBeanFactory() {
        // 主要是通过该方法完成IoC容器的刷新
        refreshBeanFactory();
        ConfigurableListableBeanFactory beanFactory = getBeanFactory();
        if (logger.isDebugEnabled()) {
            logger.debug("Bean factory for " + getDisplayName() + ": " + beanFactory);
        }
        return beanFactory;
    }
  • 进入AbstractRefreshableApplicationContextrefreshBeanFactory方法:
    • 销毁以前的容器
    • 创建新的IoC容器
    • 加载BeanDefinition对象注册到IoC容器中
protected final void refreshBeanFactory() throws BeansException {
        // 如果之前有IoC容器,则销毁
        if (hasBeanFactory()) {
            destroyBeans();
            closeBeanFactory();
        }
        try {
            // 创建IoC容器,也就是DefaultListableBeanFactory
            DefaultListableBeanFactory beanFactory = createBeanFactory();
            beanFactory.setSerializationId(getId());
            customizeBeanFactory(beanFactory);
            // 加载BeanDefinition对象,并注册到IoC容器中(重点)
            loadBeanDefinitions(beanFactory);
            synchronized (this.beanFactoryMonitor) {
                this.beanFactory = beanFactory;
            }
        }
        catch (IOException ex) {
            throw new ApplicationContextException("I/O error parsing bean definition source for " + getDisplayName(), ex);
        }
    }
  • 进入AbstractRefreshableApplicationContextcreateBeanFactory方法
 protected DefaultListableBeanFactory createBeanFactory() {
        return new DefaultListableBeanFactory(getInternalParentBeanFactory());
    }

 

posted @ 2017-11-22 16:43  Emyin  阅读(686)  评论(0编辑  收藏  举报