IoC容器的初始化过程

TIPS:本文主要是讲述在spring框架中的beanFactory初始化过程,在spring-boot稍有不同。

BeanFactory和ApplicationContext

在spring IOC容器的设计中有两个主要的容器系列:

  1. BeanFactory:实现BeanFactory接口的简单容器系列,这个系列的容器只实现了容器的最基本功能。
  2. ApplicationContext:它是容器的高级形态,继承了BeanFactory接口,应用上下文在简单容器的基础上,增加了许多面向框架的特性,同时对应用环境做了许多适配。常见的实现有:
    1. ClassPathXmlApplicationContext
    2. FileSystemXmlApplicationContext
    3. GenericXmlApplicationContext

IoC容器的设计

ApplicationContext实现的主要接口
从上图可以看到ApplicationContext实现了BeanFactory接口容器该有的功能,它也一样不少

IoC容器的初始化过程

IoC容器的初始化过程分为3歩

  1. 资源定位
  2. beanDefination载入
  3. bean注册

以FileSystemXmlApplicationContext为例进行讲解:

FileSystemXmlApplicationContext applicationContext = 
						new FileSystemXmlApplicationContext("classpath:/bean.xml");

通常手动创建ApplicationContext的步骤如上述所示。

beanDefinition的定位

/*构造器*/
public FileSystemXmlApplicationContext(String configLocation) throws BeansException {
        this(new String[]{configLocation}, true, (ApplicationContext)null);
    }
/*在构造器中调用以下方法*/
public FileSystemXmlApplicationContext(String[] configLocations, boolean refresh, 
@Nullable ApplicationContext parent) throws BeansException {
        super(parent);
        this.setConfigLocations(configLocations);
        if (refresh) {
            this.refresh();
        }
}

Ioc的触发点

在初始化FileSystemXmlApplicationContext的过程中
this.setConfigLocations(configLocations)中的configLocations是资源(BeanDefinition)所在的文件路径,而beandefinition的定位最初是在refresh()方法中触发的

refresh()方法是AbstractApplicationContext中的方法:该方法进行IoC容器的触发点

beanDefinition的载入

@Override
public void refresh() throws BeansException, IllegalStateException {
	synchronized (this.startupShutdownMonitor) {
		// Prepare this context for refreshing.
		prepareRefresh();

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

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

		try {
			// Allows post-processing of the bean factory in context subclasses.
			postProcessBeanFactory(beanFactory);

			// Invoke factory processors registered as beans in the context.
			invokeBeanFactoryPostProcessors(beanFactory);

			// Register bean processors that intercept bean creation.
			registerBeanPostProcessors(beanFactory);

				// Initialize message source for this context.
			initMessageSource();

			// 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);

			// 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();

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

obtainFreshBeanFactory()方法主要功能是获取一个ConfigurableListableBeanFactory

/*  AbstractApplicationContext#refreshBeanFactory(),
	AbstractApplicationContext#getBeanFactory()都是抽象方法,具体实现在
	AbstractRefreshableApplicationContext中实现
*/
protected ConfigurableListableBeanFactory obtainFreshBeanFactory() {
	refreshBeanFactory();
	return getBeanFactory();
}
/*AbstractRefreshableApplicationContext # refreshBeanFactory()*/
@Override
	protected final void refreshBeanFactory() throws BeansException {
		if (hasBeanFactory()) {
			destroyBeans();
			closeBeanFactory();
		}
		try {
			DefaultListableBeanFactory beanFactory = createBeanFactory();
			beanFactory.setSerializationId(getId());
			customizeBeanFactory(beanFactory);
			loadBeanDefinitions(beanFactory);
			synchronized (this.beanFactoryMonitor) {
				this.beanFactory = beanFactory;
			}
		}
		catch (IOException ex) {
			throw new ApplicationContextException("I/O error parsing bean definition source for " + getDisplayName(), ex);
		}
	}

AbstractRefreshableApplicationContextrefreshBeanFactory()方法主要干了3件事:

  1. 创建了一个DefaultListableBeanFactory
  2. 调用customizeBeanFactory(beanFactory)方法进行定制化扩展
  3. 调用loadBeanDefinitions(beanFactory)进行beanDefinition的载入,具体是由XmlBeanDefinitionReader进行载入的,资源定位也是在此时进行的。

**TIPS**:refreshBeanFactory()方法只是将xml中定义的bean进行了注册,对于由注解@Component标记的bean是在获取BeanFactory后调用invokeBeanFactoryPostProcessors(beanFactory)方法注册完成的。

(载入的过程其实就是一个将用户定义的bean转换成IoC容器内部数据结构的过程,而这个数据结构就是BeanDefinition,每一个bean都被转换成BeanDefinition)

BeanDefinition在IoC容器中的注册

在BeanDefinition在IoC容器中载入和解析过后,需要将这些BeanDefinition向IoC容器注册,在DefaultListableBeanFactory中,是通过一个HashMap来持有载入的BeanDefinition的。

private final Map<String, BeanDefinition> beanDefinitionMap = new ConcurrentHashMap(256);

将解析得到的BeanDefinition向IoC容器中的beanDefinitionMap注册的过程是在载入beanDefinition完成后进行的。
具体过程是:

XmlBeanDefinitionReader.loadBeanDefinitions(configLocations)						->
XmlBeanDefinitionReader.registerBeanDefinitions(Document doc, Resource resource)	->
DefaultBeanDefinitionDocumentReader.registerBeanDefinitions(
									Document doc, XmlReaderContext readerContext)	->
DefaultBeanDefinitionDocumentReader.parseBeanDefinitions()							->
DefaultBeanDefinitionDocumentReader.parseDefaultElement()							->
DefaultBeanDefinitionDocumentReader.processBeanDefinition()							->
BeanDefinitionReaderUtils.registerBeanDefinition()									->
DefaultListableBeanFactory.registerBeanDefinition(){
...
this.beanDefinitionMap.put(beanName, beanDefinition);
}	

以上的内容只是IoC容器初始化的过程,不涉及IoC容器的依赖注入。

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值