天天看點

org.springframework.beans包

beans包中最核心的兩個類:DefaultListableBeanFactory&XmlBeanDefinitionReader

XmlBeanFactory繼承自DefaultListableBeanFactory,而DefaultListableBeanFactory是整個bean加載的核心部分,是Spring注冊及加載bean的預設實作,而對于XmlBeanFactory與DefaultListableBeanFactory不同的地方其實是在XmlBeanFactory中使用了自定義的XML讀取器XmlBeanDefinitionReader,實作了個性化的BeanDefinitionReader讀取。

org.springframework.beans包

先簡單地了解一下上面類圖中的各個類的作用。

AliasRegistry:定義對alias的簡單增删改等操作。

SimpleAliasRegistry:主要使用map作為alias的緩存,并對接口AliasRegistry進行實作。

SingletonBeanRegistry:定義對單例的注冊及擷取。

BeanFactory:定義擷取bean及bean的各種屬性。

DefaultSingletonBeanRegistry:對接口SingletonBeanRegistry各函數的實作。

HierarchicalBeanFactory:繼承BeanFactory,也就是在BeanFactory定義的功能的基礎上增加了對parentFactory的支援。

BeanDefinitionRegistry:定義對BeanDefinition的各種增删改操作。

FactoryBeanRegistrySupport:在DefaultSingletonBeanRegistry基礎上增加了對FactoryBean的特殊處理功能。

ConfigurableBeanFactory:提供配置Factory的各種方法。

ListableBeanFactory:根據各種條件擷取bean的配置清單。

AbstractBeanFactory:綜合FactoryBeanRegistrySupport和ConfigurableBeanFactory的功能。

AutowireCapableBeanFactory:提供建立bean、自動注入、初始化以及應用bean的後處理器。

AbstractAutowireCapableBeanFactory:綜合AbstractBeanFactory并對接口AutowireCapableBeanFactory進行實作。

ConfigurableListableBeanFactory:BeanFactory配置清單,指定忽略類型及接口等。

DefaultListableBeanFactory:綜合上面所有功能,主要是對Bean注冊後的處理。

XmlBeanFactory對DefaultListableBeanFactory類進行了擴充,主要用于從XML文檔中讀取BeanDefinition,對于注冊及擷取Bean都是使用從父類DefaultListableBeanFactory繼承的方法去實作,而唯獨與父類不同的個性化實作就是增加了XmlBeanDefinitionReader類型的reader屬性。在XmlBeanFactory中主要使用reader屬性對資源檔案進行讀取和注冊。

XML配置檔案的讀取是Spring中重要的功能,因為Spring的大部分功能都是以配置作為切入點的,那麼我們可以從XmlBeanDefinitionReader中梳理一下資源檔案讀取、解析及注冊的大緻脈絡,首先看看各個類的功能。 

org.springframework.beans包

ResourceLoader:定義資源加載器,主要應用于根據給定的資源檔案位址傳回對應的Resource。

BeanDefinitionReader:主要定義資源檔案讀取并轉換為BeanDefinition的各個功能。

EnvironmentCapable:定義擷取Environment方法。

DocumentLoader:定義從資源檔案加載到轉換為Document的功能。

AbstractBeanDefinitionReader:對EnvironmentCapable、BeanDefinitionReader類定義的功能進行實作。

BeanDefinitionDocumentReader:定義讀取Docuemnt并注冊BeanDefinition功能。

BeanDefinitionParserDelegate:定義解析Element的各種方法。

在XmlBeanDifinitionReader中主要包含以下幾步的處理:

通過繼承自AbstractBeanDefinitionReader中的方法,來使用ResourLoader将資源檔案路徑轉換為對應的Resource檔案。

通過DocumentLoader對Resource檔案進行轉換,将Resource檔案轉換為Document檔案。

通過實作接口BeanDefinitionDocumentReader的DefaultBeanDefinitionDocumentReader類對Document進行解析,并使用BeanDefinitionParserDelegate對Element進行解析。