初始化时执行的类为:AbstractApplicationContext
方法是这个:
public void refresh() throws BeansException, IllegalStateException {
synchronized (this.startupShutdownMonitor) {
// Prepare this context for refreshing.
/**
*初始化一些容器所需变量,解析${}占位符变量
*/
prepareRefresh();
// Tell the subclass to refresh the internal bean factory.
/**
*核心
* 1.初始化bean工厂(包括一些自定义的工厂特征)
*2.loadBeanDefinitions(解析xml中bean为BeanDefinition)
2.1通过读取xml配置文件将配置中标签在中的元素,解析成documet(类似html的document)
2.2遍历document中的元素标签,并解析成BeanDefinition数据结构
2.3将解析后的BeanDefinition数据结构,注册到bean工厂的beanDefinitionMap中,并将beanName放入beanDefinitionNames中。2.3中如果发现容器已经在创建bean实例了,
那么需要做额外的操作,这里有待补充。另外,此处还涉及manualSingletonNames这个人工单例记录的list中,有待补充。如果该bean有重复定义,那么也有额外的处理。
*/
ConfigurableListableBeanFactory beanFactory = obtainFreshBeanFactory();
// Prepare the bean factory for use in this context.
/**
*配置beanfactory的一些参数,比如类加载器、后处理器等等
*/
prepareBeanFactory(beanFactory);
try {
// Allows post-processing of the bean factory in context subclasses.
/**
*向beanFactory注册一个servlet相关的后处理器
*/
postProcessBeanFactory(beanFactory);
// Invoke factory processors registered as beans in the context.
/**
*执行beanFactory后处理器,beanFactory后处理器保存在beanFactoryPostProcessors
*/
invokeBeanFactoryPostProcessors(beanFactory);
// Register bean processors that intercept bean creation.
/**
*遍历beanDefinitionNames找出实现了BeanPostProcessor的bean,并且最终都将其注册到beanPostProcessors
*注:BeanPostProcessor根据其实现的接口区分为:priorityOrderedPostProcessors(PriorityOrdered),
internalPostProcessors(MergedBeanDefinitionPostProcessor),
orderedPostProcessorNames(Ordered),
nonOrderedPostProcessorNames(仅BeanPostProcessor)
区分的目的是这些在后期执行时是需要考虑处理顺序的
*/
registerBeanPostProcessors(beanFactory);
// Initialize message source for this context.
/**
*初始化spring消息源
*/
initMessageSource();
// Initialize event multicaster for this context.
/**
*初始化spring应用事件广播
*/
initApplicationEventMulticaster();
// Initialize other special beans in specific context subclasses.
/**
*初始化其他的特殊的上下文类,比如:ThemeSource,不知道有什么用
*/
onRefresh();
// Check for listener beans and register them.
//检查注册事件监听器,保存在applicationListeners
registerListeners();
// Instantiate all remaining (non-lazy-init) singletons.
/**
*实例化其他非懒初始化的单例bean
*核心:
*遍历所有bean-->判断是否需要生成动态代理-->需要:生成代理返回jdk + cglib
不需要:在bean实例化之前执行实例化前beanPostProcessor-->bean实例化(反射)-->执行实例化前beanPostProcessor
*/
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();
}
}
}