这里需要贴两张图 ClassPathXmlApplicationContext 继承关系树
这张图实际没画全,最上层为
DefaultResourceLoader,该类设置classLoader,并且将配置文件 封装为Resource文件 Resrource根据传入的路径的前缀来判断采取何种封装。
AbstractApplicationContext,该类完成了大部分的IOC容器初始化工作,同时也提供了扩展接口留给子类去重载。该类的refresh()函数是核心初始化操作。
AbstractRefreshableApplicationContext,该类定义了是否允许bean在运行时是否重新定义,以及包含了beanFactory。该类主要是和beanFactory打交道。
AbstractRefreshableConfigApplicationContext,该类保存了配置文件路径
AbstractXmlApplicationContext:该类封装了如何读取Resource封装的配置
最后ClassPathXmlApplicationContext:只提供了一个简单的构造函数
Spring 将类职责分开,形成职责链,每一层次的扩展 都只是添加了某个功能
然后父类定义大量的模板,让子类实现,父类层层传递到子类 知道某个子类重载了抽象方法。这里应用到了职责链设计模式和模板设计模式,IOC是个容器工厂设计模式。
IOC容器的行为也跟其组件有关,这可以认为是策略模式。
现在根据这个调用流程图 我们大概就可以了解到 Spring容器初始化的最主要的工作就是refresh()函数所做的
AbstractApplicationContext: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.
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();
}
}
}
事实上 我们看到的这些方法 可以认为是一种模板设计模式 里面有些方法 并没有实现 只是一个在AbstractApplicationContext所定义的抽象方法,这些抽象方法直到某一子类才得以实现。一般refresh()函数调用完成 那么ioc容器也就进入了可以使用的阶段。