Spring初始化Ioc容器很重要的一個方法是由ApplicationContext子接口ConfigurableApplicationContext提供的refresh(),這個方法的作用是創建加載Spring容器配置(包括.xml配置,property文件和數據庫模式等)。下面是各個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.
//主要是創建beanFactory,同時加載配置文件.xml中的beanDefinition
//通過String[] configLocations = getConfigLocations()獲取資源路徑,然後加載beanDefinition
ConfigurableListableBeanFactory beanFactory = obtainFreshBeanFactory();
// Prepare the bean factory for use in this context.
//給beanFactory註冊一些標準組建,如ClassLoader,StandardEnvironment,BeanProcess
prepareBeanFactory(beanFactory);
try {
// Allows post-processing of the bean factory in context subclasses.
//提供給子類實現一些postProcess的註冊,如AbstractRefreshableWebApplicationContext註冊一些Servlet相關的
//postProcess,真對web進行生命週期管理的Scope,通過registerResolvableDependency()方法註冊指定ServletRequest,HttpSession,WebRequest對象的工廠方法
postProcessBeanFactory(beanFactory);
// Invoke factory processors registered as beans in the context.
//調用所有BeanFactoryProcessor的postProcessBeanFactory()方法
invokeBeanFactoryPostProcessors(beanFactory);
// Register bean processors that intercept bean creation.
//註冊BeanPostProcessor,BeanPostProcessor作用是用於攔截Bean的創建
registerBeanPostProcessors(beanFactory);
// Initialize message source for this context.
//初始化消息Bean
initMessageSource();
// Initialize event multicaster for this context.
//初始化上下文的事件多播組建,ApplicationEvent觸發時由multicaster通知給ApplicationListener
initApplicationEventMulticaster();
// Initialize other special beans in specific context subclasses.
//ApplicationContext初始化一些特殊的bean
onRefresh();
// Check for listener beans and register them.
//註冊事件監聽器,事件監聽Bean統一註冊到multicaster裏頭,ApplicationEvent事件觸發後會由multicaster廣播
registerListeners();
// Instantiate all remaining (non-lazy-init) singletons.
//非延遲加載的單例Bean實例化
finishBeanFactoryInitialization(beanFactory);
// Last step: publish corresponding event.
finishRefresh();
}
catch (BeansException ex) {
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;
}
}
}