Spring容器的创建刷新
refresh() 方法
Spring 容器的创建过程主要在 refresh() 方法中
public void refresh() throws BeansException, IllegalStateException {
synchronized (this.startupShutdownMonitor) {
// 1、Prepare this context for refreshing.
prepareRefresh();
///2、Tell the subclass to refresh the internal bean factory.
ConfigurableListableBeanFactory beanFactory = obtainFreshBeanFactory();
///3、Prepare the bean factory for use in this context.
prepareBeanFactory(beanFactory);
try {
//4、 Allows post-processing of the bean factory in context subclasses.
postProcessBeanFactory(beanFactory);
//5、 Invoke factory processors registered as beans in the context.
invokeBeanFactoryPostProcessors(beanFactory);
//6、 Register bean processors that intercept bean creation.
registerBeanPostProcessors(beanFactory);
//7、 Initialize message source for this context.
initMessageSource();
//8、 Initialize event multicaster for this context.
initApplicationEventMulticaster();
//9、 Initialize other special beans in specific context subclasses.
onRefresh();
//10、 Check for listener beans and register them.
registerListeners();
//11、 Instantiate all remaining (non-lazy-init) singletons.
finishBeanFactoryInitialization(beanFactory);
//12、 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();
}
}
}
- prepareRefresh():刷新前准备
- 设置一些状态标记:比如启动时间 startupDate、closed/active 状态
- initPropertySources() 设置 init 属性,此方法交给子类实现
- getEnvironment().validateRequiredProperties(),如果没有 Environment,则 new StandardEnvironment(),然后再调用 validateRequiredProperties() 校验参数
- earlyApplicationEvents = new LinkedHashSet():保存容器中的一些早期事件
- obtainFreshBeanFactory():获取 BeanFactory
- refreshBeanFactory() 刷新 BeanFactory,在 GenericApplicationContext 的构造方法中 new 一个 DefaultListableBeanFactory,通过
this.beanFactory().setSerialization(getID());
设置一个唯一的 ID - getBeanFactory() 返回刚才 GenericApplicationContext 创建的 BeanFactory 对象
- refreshBeanFactory() 刷新 BeanFactory,在 GenericApplicationContext 的构造方法中 new 一个 DefaultListableBeanFactory,通过
- prepareBeanFactory(beanFactory): BeanFactory 的准备工作
- 设置 BeanFactory 的类加载器、表达式解析器(StandardBeanExpressionResolver)、ResourceEditorRegistrar
- 添加 BeanPostProcessor
-------待续-----------