Spring源码之一(定位、加载、注册)

1.阅读前言

Spring框架的核心是IOC和AOP,而IOC流程可以分为两个主线,第一条主线是启动容器时候针对配置文件进行加载解析,第二条主线是从容器中获取实例对象的时候,容器进行的初始化。这篇文章主要针对第一条主线进行详细分析。

2.容器核心接口

2.1 BeanFactory

2.1.1 主要方法及属性

 2.1.2 作用

BeanFactory中主要定义了容器的基本功能方法,获取实例,判断实例Scope类型等

2.2 ApplicationContext

2.2.1 

 根据类图,可以知道,ApplicationContext继承了BeanFactory、ResourceLoader、MessageSource、ApplicationEventPublisher,所以ApplicationContext不仅仅拥有容器的功能,同时支持不同的信息源(国际化),访问资源,应用事件等功能。

3.定位、加载、注册主流程

 4. refresh()方法详解

提示:这个方法代表了容器启动时的主要动作

@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.
			//子类中启动refreshBeanFactory()的地方,同时也是定位,加载,注册的地方
			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.
				//设置BeanFactory的后置处理
				postProcessBeanFactory(beanFactory);

				// Invoke factory processors registered as beans in the context.
				//调用BeanFactory的后处理器
				invokeBeanFactoryPostProcessors(beanFactory);

				// Register bean processors that intercept bean creation.
				//注册Bean的后处理器,在Bean创建过程中调用
				registerBeanPostProcessors(beanFactory);

				// Initialize message source for this context.
				//对上下文中的消息源进行初始化
				initMessageSource();

				// Initialize event multicaster for this context.
				//初始化上下文中的事件机制
				initApplicationEventMulticaster();

				// Initialize other special beans in specific context subclasses.
				//初始化其它的特殊Bean
				onRefresh();

				// Check for listener beans and register them.
				//检查监听Bean并注册
				registerListeners();

				// Instantiate all remaining (non-lazy-init) singletons.
				//实例化所有的(非non-lazy-init)单实例
				finishBeanFactoryInitialization(beanFactory);

				// Last step: publish corresponding event.
				//发布容器事件,结束Refresh过程
				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();
			}
		}

5.简化流程

猜你喜欢

转载自blog.csdn.net/ly853602/article/details/92417229