上一篇博文介紹了Spring有三個核心組件,分別是Bean組件,Context組件和Core組件,這一篇詳細介紹每個組件。
Bean組件
Bean組件對Spring非常重要。Bean組件在Spring的org.springframework.beans包下。這個包下的所有類主要解決了三件事:Bean的定義,Bean的創建以及對Bean的解析。對Spring的使用者來說唯一需要關心的就是Bean的創建,其他兩個由Spring在內部幫你完成了,對你來說是透明的。
Spring Bean的創建是典型的工廠模式,它的頂級接口是BeanFactory。下圖是Bean工廠的繼承關係:
Context組件
Context組件在Spring的org.springframework.context包下,Context實際上就是給Spring提供了一個運行時的環境,用以保存各個對象的狀態。
ApplicationContext是Context的頂級父類,他除了能標識一個應用環境的基本信息外,他還繼承了五個接口,這五個接口主要是擴展了Context的功能。下面是Context的類結構圖:
從上圖中可以看出 ApplicationContext 繼承了 BeanFactory,這也說明了 Spring 容器中運行的主體對象是 Bean,另外 ApplicationContext 繼承了 ResourceLoader 接口,使得 ApplicationContext 可以訪問到任何外部資源,這將在 Core 中詳細說明。
總體來說ApplicationContext必須要完成以下幾件事:
- 標識一個應用環境
- 利用BeanFactory創建Bean對象
- 保存對象關係表
- 能夠捕獲各種事件
Context作爲Spring的IOC容器,基本上整合了Spring的大部分功能,或者說是大部分功能的基礎。
Core組件
Core 組件作爲 Spring 的核心組件,他其中包含了很多的關鍵類,其中一個重要組成部分就是定義了資源的訪問方式。這種把所有資源都抽象成一個接口的方式很值得在以後的設計中拿來學習。
IOC容器如何工作
IOC容器實際上就是Context組件結合其他兩個組件共同構建了一個Bean關係網, 如何構建這個關係網?構建的入口就在AbstractApplicationContext 類的refresh方法中。這個方法的代碼如下:
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) {
// Destroy already created singletons to avoid dangling resources.
destroyBeans();
// Reset 'active' flag.
cancelRefresh(ex);
// Propagate exception to caller.
throw ex;
}
}
}
這個方法就是構建整個 Ioc 容器過程的完整的代碼,瞭解了裏面的每一行代碼基本上就瞭解大部分 Spring 的原理和功能了。
這段代碼主要包含了這樣幾個步驟:
- 構建BeanFactory,以便於產生所需的“演員”
- 註冊可能感興趣的事件
- 創建Bean實例對象
- 觸發被監聽的事件