AbstractApplicationContext的refresh方法是提纲挈领的一个方法。这个方法如果全部读懂了,基本上Spring的源码就Over完了。下面先贴上refresh的方法源码
public void refresh() throws BeansException, IllegalStateException {
synchronized (this.startupShutdownMonitor) {
prepareRefresh();
ConfigurableListableBeanFactory beanFactory = obtainFreshBeanFactory();
prepareBeanFactory(beanFactory);
try {
postProcessBeanFactory(beanFactory);
invokeBeanFactoryPostProcessors(beanFactory);
registerBeanPostProcessors(beanFactory);
initMessageSource();
initApplicationEventMulticaster();
onRefresh();
registerListeners();
finishBeanFactoryInitialization(beanFactory);
finishRefresh();
}
catch (BeansException ex) {
if (logger.isWarnEnabled()) {
logger.warn("Exception encountered during context initialization -cancelling refresh attempt: " + ex);
}
destroyBeans();
cancelRefresh(ex);
throw ex;
}
finally {
resetCommonCaches();
}
}
}
下面开始仔细分析各种方法的功能:
1.prepareRefresh
protected void prepareRefresh() {
this.startupDate = System.currentTimeMillis();
this.closed.set(false);
this.active.set(true);
if (logger.isDebugEnabled()) {
if (logger.isTraceEnabled()) {
logger.trace("Refreshing " + this);
}
else {
logger.debug("Refreshing " + getDisplayName());
}
}
// Initialize any placeholder property sources in the context environment
initPropertySources();
// Validate that all properties marked as required are resolvable
// see ConfigurablePropertyResolver#setRequiredProperties
getEnvironment().validateRequiredProperties();
// Allow for the collection of early ApplicationEvents,
// to be published once the multicaster is available...
this.earlyApplicationEvents = new LinkedHashSet<>();
}
功能:做一些刷新之前的准备工作。例如:设置下active和closed标志;记录下refresh开始的时间.或者是初始化一下property属性配置信息的资源(这个在Web方面用到了,会初始化servletConfig信息).
下面的那句:getEnvironment().validateRequiredProperties()会对上面的initPropertySources()初始化的信息进行验证工作,具体的验证逻辑,我也没看,所以,暂且放这儿不说,以后专门补充写这个细节。
2.obtainFreshBeanFactory
protected ConfigurableListableBeanFactory obtainFreshBeanFactory() {
refreshBeanFactory();
return getBeanFactory();
}
功能:刷新Bean的工程,然后获取到Bean的工厂。原先我以为是就是重新new一个BeanFactory,结果不是那么简单,原来XML的解析,生成BeanDefinition,之后load进去都是在这个方法做的。所以这个需要专门做一个文章来解释。
未完待续,先贴上再说