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();
流程解析
-
进入AbstractApplication的
obtainFreshBeanFactory
方法:用于创建一个新的
IoC容器
,这个IoC容器
就是DefaultListableBeanFactory对象。
protected ConfigurableListableBeanFactory obtainFreshBeanFactory() { // 主要是通过该方法完成IoC容器的刷新 refreshBeanFactory(); ConfigurableListableBeanFactory beanFactory = getBeanFactory(); if (logger.isDebugEnabled()) { logger.debug("Bean factory for " + getDisplayName() + ": " + beanFactory); } return beanFactory; }
- 进入AbstractRefreshableApplicationContext的
refreshBeanFactory
方法:- 销毁以前的容器
- 创建新的
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); } }
- 进入AbstractRefreshableApplicationContext的
createBeanFactory
方法
protected DefaultListableBeanFactory createBeanFactory() { return new DefaultListableBeanFactory(getInternalParentBeanFactory()); }