一、ApplicationContext的设计路线
上下文对容器不仅是扩展关系,更重要是持有关系,上下文是以属性形式持有了容器
二、ApplicationContext接口
上下文的顶级容器
public interface ApplicationContext extends EnvironmentCapable, ListableBeanFactory, HierarchicalBeanFactory,
MessageSource, ApplicationEventPublisher, ResourcePatternResolver {
}
三、ConfigurableApplicationContext接口
核心方法:
refresh():IoC容器的初始化过程,标志着IoC容器的正式启动
四、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();
}
}
}
其中最核心的两个方法:
invokeBeanFactoryPostProcessors(beanFactory):在IoC容器中建立BeanDefinition数据映射
扫描类,然后将其封装为BeanDefinition,并放入DefaultListableBeanFactory的Map<String, BeanDefinition> beanDefinitionMap里
finishBeanFactoryInitialization(beanFactory):初始化bean
遍历DefaultListableBeanFactory的Map<String, BeanDefinition> beanDefinitionMap,拿出BeanDefinition,并其代表的bean实例化
五、GenericApplicationContext
属性DefaultListableBeanFactory beanFactory
public class GenericApplicationContext extends AbstractApplicationContext implements BeanDefinitionRegistry {
private final DefaultListableBeanFactory beanFactory;
...
}
六、AnnotationConfigServletWebServerApplicationContext
继承自GenericApplicationContext,属性beanFactory是IoC容器(DefaultListableBeanFactory)