前几天,面试高级java工程师,被问到spring的ioc容器是咋样实现的。悲催的居然忘记了。回来之后好好的看看spring的IOC源代码,了解具体实现,在此记下,下次不要再出丑了。
1. 启动ContextLoaderListener监听器。
2. 初始化initWebApplicationContext。
3. this.context = createWebApplicationContext(servletContext, parent);
4 wac.refresh();
5 obtainFreshBeanFactory();
6 loadBeanDefinitions(beanFactory);
获取 applicationContext.xml 配置文件
7 documentReader.registerBeanDefinitions(doc, createReaderContext(resource))
读取上面的XML文件,将bean注册到spring的容器中。
其中 registerBeanDefinitions
public void registerBeanDefinitions(Document doc, XmlReaderContext readerContext) {
this.readerContext = readerContext;
logger.debug("Loading bean definitions");
Element root = doc.getDocumentElement();
BeanDefinitionParserDelegate delegate = createHelper(readerContext, root);
preProcessXml(root);
// 先将XML解析,然后将解析后的Bean信息存放到BeanDefinition,spring中有个beanDefinitionMap用于保存BeanDefinition
parseBeanDefinitions(root, delegate);
postProcessXml(root);
}
------------
public void refresh() throws BeansException, IllegalStateException {
synchronized (this.startupShutdownMonitor) {
// Prepare this context for refreshing.
prepareRefresh();
// Tell the subclass to refresh the internal bean factory.
// 关闭释放旧的beanFactory创建新的beanFactory,读取配置文件等
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.
// 下面两行主要用户扩展,处理所有已注册的BeanFactoryPostProcessor,实现在已经加载配置但未初始化bean时对配置进行修改
postProcessBeanFactory(beanFactory);
// Invoke factory processors registered as beans in the context.
invokeBeanFactoryPostProcessors(beanFactory);
// Register bean processors that intercept bean creation.
// 处理所有已注册的BeanPostProcessor,主要用于扩展,实现bean初始化前后的一些定制操作
registerBeanPostProcessors(beanFactory);
// Initialize message source for this context.
// 初始化消息源bean
initMessageSource();
// Initialize event multicaster for this context.
// 初始化事件监听器集,也有人叫事件监听器的注册表,所有的事件监听器都在这个bean里进行管理
initApplicationEventMulticaster();
// Initialize other special beans in specific context subclasses.
// 主要用于扩展,实现一些特殊bean的初始化,时间点是类似消息源事件监听器集等特殊bean初始化后,普通的bean初始化前
onRefresh();
// Check for listener beans and register them.
// 注册监听器
registerListeners();
// Instantiate all remaining (non-lazy-init) singletons.
// 初始化其余的非延迟加载的单例bean
finishBeanFactoryInitialization(beanFactory);
// Last step: publish corresponding event.
// 刷新完成调用LifecycleProcessor的onRefresh方法,并且发布ContextRefreshedEvent事件
finishRefresh();
}
catch (BeansException ex) {
// Destroy already created singletons to avoid dangling resources.
destroyBeans();
// Reset 'active' flag.
cancelRefresh(ex);
// Propagate exception to caller.
throw ex;
}
}
}