上面两张图揭示了Spring中重要的容器工厂,彼此之间的关系。BeanFactory作为最原始的定义,下面有两个重点的类值的关注,
DefaultListableBeanFactory和AbstractApplicationContext
DefaultListableBeanFactory这个类是一个非常完全的BeanFactory,基于bean的定义元数据,通过后置处理器来提供可扩展性。 但是现在基本没有使用了
AbstractApplicationContext 是常用的IOC容器的抽象类,里面已经定义了比较完善的方法实现
基于上面的了解,我们总体来看下Spring启动经历的事情,后面会分多个篇章来归纳整个过程
@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();
}
}
}
参考文档
https://www.cnblogs.com/coder-qi/p/11296591.html
https://www.jianshu.com/p/f9718de489f0
https://www.cnblogs.com/coder-qi/p/11086695.html#applicationcontext%E8%AE%BE%E8%AE%A1%E8%A7%A3%E6%9E%90