在認(rèn)真學(xué)習(xí)Rod.Johnson的三部曲之一:<<Professional Java Development with the spring framework>>,順便也看了看源代碼想知道個究竟,拋磚引玉,有興趣的同志一起討論研究吧!
以下內(nèi)容引自博客:
http://jiwenke-spring.blogspot.com/,歡迎指導(dǎo):)
在Spring中,IOC容器的重要地位我們就不多說了,對于Spring的使用者而言,IOC容器實際上是什么呢?我們可以說BeanFactory就是我們看到的IoC容器,當(dāng)然了Spring為我們準(zhǔn)備了許多種IoC容器來使用,這樣可以方便我們從不同的層面,不同的資源位置,不同的形式的定義信息來建立我們需要的IoC容器。
在Spring中,最基本的IOC容器接口是BeanFactory - 這個接口為具體的IOC容器的實現(xiàn)作了最基本的功能規(guī)定 - 不管怎么著,作為IOC容器,這些接口你必須要滿足應(yīng)用程序的最基本要求:
- public interface BeanFactory {
-
-
-
- String FACTORY_BEAN_PREFIX = "&";
-
-
-
- Object getBean(String name) throws BeansException;
-
-
- Object getBean(String name, Class requiredType) throws BeansException;
-
-
- boolean containsBean(String name);
-
-
- boolean isSingleton(String name) throws NoSuchBeanDefinitionException;
-
-
- Class getType(String name) throws NoSuchBeanDefinitionException;
-
-
- String[] getAliases(String name);
-
- }
public interface BeanFactory {
//這里是對FactoryBean的轉(zhuǎn)義定義,因為如果使用bean的名字檢索FactoryBean得到的對象是工廠生成的對象,
//如果需要得到工廠本身,需要轉(zhuǎn)義
String FACTORY_BEAN_PREFIX = "&";
//這里根據(jù)bean的名字,在IOC容器中得到bean實例,這個IOC容器就是一個大的抽象工廠。
Object getBean(String name) throws BeansException;
//這里根據(jù)bean的名字和Class類型來得到bean實例,和上面的方法不同在于它會拋出異常:如果根據(jù)名字取得的bean實例的Class類型和需要的不同的話。
Object getBean(String name, Class requiredType) throws BeansException;
//這里提供對bean的檢索,看看是否在IOC容器有這個名字的bean
boolean containsBean(String name);
//這里根據(jù)bean名字得到bean實例,并同時判斷這個bean是不是單件
boolean isSingleton(String name) throws NoSuchBeanDefinitionException;
//這里對得到bean實例的Class類型
Class getType(String name) throws NoSuchBeanDefinitionException;
//這里得到bean的別名,如果根據(jù)別名檢索,那么其原名也會被檢索出來
String[] getAliases(String name);
}
在BeanFactory里只對IOC容器的基本行為作了定義,根本不關(guān)心你的bean是怎樣定義怎樣加載的 - 就像我們只關(guān)心從這個工廠里我們得到到什么產(chǎn)品對象,至于工廠是怎么生產(chǎn)這些對象的,這個基本的接口不關(guān)心這些。如果要關(guān)心工廠是怎樣產(chǎn)生對象的,應(yīng)用程序需要使用具體的IOC容器實現(xiàn)- 當(dāng)然你可以自己根據(jù)這個BeanFactory來實現(xiàn)自己的IOC容器,但這個沒有必要,因為Spring已經(jīng)為我們準(zhǔn)備好了一系列工廠來讓我們使用。比如XmlBeanFactory就是針對最基礎(chǔ)的BeanFactory的IOC容器的實現(xiàn) - 這個實現(xiàn)使用xml來定義IOC容器中的bean。
Spring提供了一個BeanFactory的基本實現(xiàn),XmlBeanFactory同樣的通過使用模板模式來得到對IOC容器的抽象- AbstractBeanFactory,DefaultListableBeanFactory這些抽象類為其提供模板服務(wù)。其中通過resource 接口來抽象bean定義數(shù)據(jù),對Xml定義文件的解析通過委托給XmlBeanDefinitionReader來完成。下面我們根據(jù)書上的例子,簡單的演示IOC容器的創(chuàng)建過程:
- ClassPathResource res = new ClassPathResource("beans.xml");
- DefaultListableBeanFactory factory = new DefaultListableBeanFactory();
- XmlBeanDefinitionReader reader = new XmlBeanDefinitionReader(factory);
- reader.loadBeanDefinitions(res);
ClassPathResource res = new ClassPathResource("beans.xml");
DefaultListableBeanFactory factory = new DefaultListableBeanFactory();
XmlBeanDefinitionReader reader = new XmlBeanDefinitionReader(factory);
reader.loadBeanDefinitions(res);
這些代碼演示了以下幾個步驟:
1. 創(chuàng)建IOC配置文件的抽象資源
2. 創(chuàng)建一個BeanFactory
3. 把讀取配置信息的BeanDefinitionReader,這里是XmlBeanDefinitionReader配置給BeanFactory
4. 從定義好的資源位置讀入配置信息,具體的解析過程由XmlBeanDefinitionReader來完成,這樣完成整個載入bean定義的過程。我們的IoC容器就建立起來了。在BeanFactory的源代碼中我們可以看到:
- public class XmlBeanFactory extends DefaultListableBeanFactory {
-
- private final XmlBeanDefinitionReader reader = new XmlBeanDefinitionReader(this);
- public XmlBeanFactory(Resource resource) throws BeansException {
- this(resource, null);
- }
-
- public XmlBeanFactory(Resource resource, BeanFactory parentBeanFactory) throws BeansException {
- super(parentBeanFactory);
- this.reader.loadBeanDefinitions(resource);
- }
public class XmlBeanFactory extends DefaultListableBeanFactory {
//這里為容器定義了一個默認(rèn)使用的bean定義讀取器
private final XmlBeanDefinitionReader reader = new XmlBeanDefinitionReader(this);
public XmlBeanFactory(Resource resource) throws BeansException {
this(resource, null);
}
//在初始化函數(shù)中使用讀取器來對資源進(jìn)行讀取,得到bean定義信息。
public XmlBeanFactory(Resource resource, BeanFactory parentBeanFactory) throws BeansException {
super(parentBeanFactory);
this.reader.loadBeanDefinitions(resource);
}
我們在后面會看到讀取器讀取資源和注冊bean定義信息的整個過程,基本上是和上下文的處理是一樣的,從這里我們可以看到上下文和 XmlBeanFactory這兩種IOC容器的區(qū)別,BeanFactory往往不具備對資源定義的能力,而上下文可以自己完成資源定義,從這個角度上看上下文更好用一些。
仔細(xì)分析Spring BeanFactory的結(jié)構(gòu),我們來看看在BeanFactory基礎(chǔ)上擴(kuò)展出的ApplicationContext - 我們最常使用的上下文。除了具備BeanFactory的全部能力,上下文為應(yīng)用程序又增添了許多便利:
* 可以支持不同的信息源,我們看到ApplicationContext擴(kuò)展了MessageSource
* 訪問資源 , 體現(xiàn)在對ResourceLoader和Resource的支持上面,這樣我們可以從不同地方得到bean定義資源
* 支持應(yīng)用事件,繼承了接口ApplicationEventPublisher,這樣在上下文中引入了事件機(jī)制而BeanFactory是沒有的。
ApplicationContext允許上下文嵌套 - 通過保持父上下文可以維持一個上下文體系 - 這個體系我們在以后對Web容器中的上下文環(huán)境的分析中可以清楚地看到。對于bean的查找可以在這個上下文體系中發(fā)生,首先檢查當(dāng)前上下文,其次是父上下文,逐級向上,這樣為不同的Spring應(yīng)用提供了一個共享的bean定義環(huán)境。這個我們在分析Web容器中的上下文環(huán)境時也能看到。
ApplicationContext提供IoC容器的主要接口,在其體系中有許多抽象子類比如AbstractApplicationContext為具體的BeanFactory的實現(xiàn),比如FileSystemXmlApplicationContext和 ClassPathXmlApplicationContext提供上下文的模板,使得他們只需要關(guān)心具體的資源定位問題。當(dāng)應(yīng)用程序代碼實例化 FileSystemXmlApplicationContext的時候,得到IoC容器的一種具體表現(xiàn) - ApplicationContext,從而應(yīng)用程序通過ApplicationContext來管理對bean的操作。
BeanFactory 是一個接口,在實際應(yīng)用中我們一般使用ApplicationContext來使用IOC容器,它們也是IOC容器展現(xiàn)給應(yīng)用開發(fā)者的使用接口。對應(yīng)用程序開發(fā)者來說,可以認(rèn)為BeanFactory和ApplicationFactory在不同的使用層面上代表了SPRING提供的IOC容器服務(wù)。
下面我們具體看看通過FileSystemXmlApplicationContext是怎樣建立起IOC容器的, 顯而易見我們可以通過new來得到IoC容器:
- ApplicationContext = new FileSystemXmlApplicationContext(xmlPath);
ApplicationContext = new FileSystemXmlApplicationContext(xmlPath);
調(diào)用的是它初始化代碼:
- public FileSystemXmlApplicationContext(String[] configLocations, boolean refresh, ApplicationContext parent)
- throws BeansException {
- super(parent);
- this.configLocations = configLocations;
- if (refresh) {
-
- refresh();
- }
- }
public FileSystemXmlApplicationContext(String[] configLocations, boolean refresh, ApplicationContext parent)
throws BeansException {
super(parent);
this.configLocations = configLocations;
if (refresh) {
//這里是IoC容器的初始化過程,其初始化過程的大致步驟由AbstractApplicationContext來定義
refresh();
}
}
refresh的模板在AbstractApplicationContext:
- public void refresh() throws BeansException, IllegalStateException {
- synchronized (this.startupShutdownMonitor) {
- synchronized (this.activeMonitor) {
- this.active = true;
- }
-
-
- refreshBeanFactory();
- ............
- }
public void refresh() throws BeansException, IllegalStateException {
synchronized (this.startupShutdownMonitor) {
synchronized (this.activeMonitor) {
this.active = true;
}
// 這里需要子類來協(xié)助完成資源位置定義,bean載入和向IOC容器注冊的過程
refreshBeanFactory();
............
}
這個方法包含了整個BeanFactory初始化的過程,對于特定的FileSystemXmlBeanFactory,我們看到定位資源位置由refreshBeanFactory()來實現(xiàn):
在AbstractXmlApplicationContext中定義了對資源的讀取過程,默認(rèn)由XmlBeanDefinitionReader來讀取:
- protected void loadBeanDefinitions(DefaultListableBeanFactory beanFactory) throws IOException {
-
- XmlBeanDefinitionReader beanDefinitionReader = new XmlBeanDefinitionReader(beanFactory);
-
-
-
- beanDefinitionReader.setResourceLoader(this);
- beanDefinitionReader.setEntityResolver(new ResourceEntityResolver(this));
-
- initBeanDefinitionReader(beanDefinitionReader);
-
- loadBeanDefinitions(beanDefinitionReader);
- }
protected void loadBeanDefinitions(DefaultListableBeanFactory beanFactory) throws IOException {
// 這里使用XMLBeanDefinitionReader來載入bean定義信息的XML文件
XmlBeanDefinitionReader beanDefinitionReader = new XmlBeanDefinitionReader(beanFactory);
//這里配置reader的環(huán)境,其中ResourceLoader是我們用來定位bean定義信息資源位置的
///因為上下文本身實現(xiàn)了ResourceLoader接口,所以可以直接把上下文作為ResourceLoader傳遞給XmlBeanDefinitionReader
beanDefinitionReader.setResourceLoader(this);
beanDefinitionReader.setEntityResolver(new ResourceEntityResolver(this));
initBeanDefinitionReader(beanDefinitionReader);
//這里轉(zhuǎn)到定義好的XmlBeanDefinitionReader中對載入bean信息進(jìn)行處理
loadBeanDefinitions(beanDefinitionReader);
}
轉(zhuǎn)到beanDefinitionReader中進(jìn)行處理:
- protected void loadBeanDefinitions(XmlBeanDefinitionReader reader) throws BeansException, IOException {
- Resource[] configResources = getConfigResources();
- if (configResources != null) {
-
- reader.loadBeanDefinitions(configResources);
- }
- String[] configLocations = getConfigLocations();
- if (configLocations != null) {
- reader.loadBeanDefinitions(configLocations);
- }
- }
protected void loadBeanDefinitions(XmlBeanDefinitionReader reader) throws BeansException, IOException {
Resource[] configResources = getConfigResources();
if (configResources != null) {
//調(diào)用XmlBeanDefinitionReader來載入bean定義信息。
reader.loadBeanDefinitions(configResources);
}
String[] configLocations = getConfigLocations();
if (configLocations != null) {
reader.loadBeanDefinitions(configLocations);
}
}
而在作為其抽象父類的AbstractBeanDefinitionReader中來定義載入過程:
- public int loadBeanDefinitions(String location) throws BeanDefinitionStoreException {
-
- ResourceLoader resourceLoader = getResourceLoader();
- .........
- if (resourceLoader instanceof ResourcePatternResolver) {
-
- try {
- Resource[] resources = ((ResourcePatternResolver) resourceLoader).getResources(location);
- int loadCount = loadBeanDefinitions(resources);
- return loadCount;
- }
- ........
- }
- else {
-
- Resource resource = resourceLoader.getResource(location);
-
- int loadCount = loadBeanDefinitions(resource);
- return loadCount;
- }
- }
public int loadBeanDefinitions(String location) throws BeanDefinitionStoreException {
//這里得到當(dāng)前定義的ResourceLoader,默認(rèn)的我們使用DefaultResourceLoader
ResourceLoader resourceLoader = getResourceLoader();
.........//如果沒有找到我們需要的ResourceLoader,直接拋出異常
if (resourceLoader instanceof ResourcePatternResolver) {
// 這里處理我們在定義位置時使用的各種pattern,需要ResourcePatternResolver來完成
try {
Resource[] resources = ((ResourcePatternResolver) resourceLoader).getResources(location);
int loadCount = loadBeanDefinitions(resources);
return loadCount;
}
........
}
else {
// 這里通過ResourceLoader來完成位置定位
Resource resource = resourceLoader.getResource(location);
// 這里已經(jīng)把一個位置定義轉(zhuǎn)化為Resource接口,可以供XmlBeanDefinitionReader來使用了
int loadCount = loadBeanDefinitions(resource);
return loadCount;
}
}
當(dāng)我們通過ResourceLoader來載入資源,別忘了了我們的GenericApplicationContext也實現(xiàn)了ResourceLoader接口:
- public class GenericApplicationContext extends AbstractApplicationContext implements BeanDefinitionRegistry {
- public Resource getResource(String location) {
-
- if (this.resourceLoader != null) {
- return this.resourceLoader.getResource(location);
- }
- return super.getResource(location);
- }
- .......
- }
public class GenericApplicationContext extends AbstractApplicationContext implements BeanDefinitionRegistry {
public Resource getResource(String location) {
//這里調(diào)用當(dāng)前的loader也就是DefaultResourceLoader來完成載入
if (this.resourceLoader != null) {
return this.resourceLoader.getResource(location);
}
return super.getResource(location);
}
.......
}
而我們的FileSystemXmlApplicationContext就是一個DefaultResourceLoader - GenericApplicationContext()通過DefaultResourceLoader:
- public Resource getResource(String location) {
-
- if (location.startsWith(CLASSPATH_URL_PREFIX)) {
- return new ClassPathResource(location.substring(CLASSPATH_URL_PREFIX.length()), getClassLoader());
- }
- else {
- try {
-
- URL url = new URL(location);
- return new UrlResource(url);
- }
- catch (MalformedURLException ex) {
-
- return getResourceByPath(location);
- }
- }
- }
public Resource getResource(String location) {
//如果是類路徑的方式,那需要使用ClassPathResource來得到bean文件的資源對象
if (location.startsWith(CLASSPATH_URL_PREFIX)) {
return new ClassPathResource(location.substring(CLASSPATH_URL_PREFIX.length()), getClassLoader());
}
else {
try {
// 如果是URL方式,使用UrlResource作為bean文件的資源對象
URL url = new URL(location);
return new UrlResource(url);
}
catch (MalformedURLException ex) {
// 如果都不是,那我們只能委托給子類由子類來決定使用什么樣的資源對象了
return getResourceByPath(location);
}
}
}
我們的FileSystemXmlApplicationContext本身就是是DefaultResourceLoader的實現(xiàn)類,他實現(xiàn)了以下的接口:
- protected Resource getResourceByPath(String path) {
- if (path != null && path.startsWith("/")) {
- path = path.substring(1);
- }
-
- return new FileSystemResource(path);
- }
protected Resource getResourceByPath(String path) {
if (path != null && path.startsWith("/")) {
path = path.substring(1);
}
//這里使用文件系統(tǒng)資源對象來定義bean文件
return new FileSystemResource(path);
}
這樣代碼就回到了FileSystemXmlApplicationContext中來,他提供了FileSystemResource來完成從文件系統(tǒng)得到配置文件的資源定義。這樣,就可以從文件系統(tǒng)路徑上對IOC配置文件進(jìn)行加載 - 當(dāng)然我們可以按照這個邏輯從任何地方加載,在Spring中我們看到它提供的各種資源抽象,比如ClassPathResource, URLResource,FileSystemResource等來供我們使用。上面我們看到的是定位Resource的一個過程,而這只是加載過程的一部分 - 我們回到AbstractBeanDefinitionReaderz中的loadDefinitions(resource)來看看得到代表bean文件的資源定義以后的載入過程,默認(rèn)的我們使用XmlBeanDefinitionReader:
- public int loadBeanDefinitions(EncodedResource encodedResource) throws BeanDefinitionStoreException {
- .......
- try {
-
- InputStream inputStream = encodedResource.getResource().getInputStream();
- try {
-
- InputSource inputSource = new InputSource(inputStream);
- if (encodedResource.getEncoding() != null) {
- inputSource.setEncoding(encodedResource.getEncoding());
- }
-
- return doLoadBeanDefinitions(inputSource, encodedResource.getResource());
- }
- finally {
-
- inputStream.close();
- }
- }
- .........
- }
-
- protected int doLoadBeanDefinitions(InputSource inputSource, Resource resource)
- throws BeanDefinitionStoreException {
- try {
- int validationMode = getValidationModeForResource(resource);
-
- Document doc = this.documentLoader.loadDocument(
- inputSource, this.entityResolver, this.errorHandler, validationMode, this.namespaceAware);
- return registerBeanDefinitions(doc, resource);
- }
- .......
- }
public int loadBeanDefinitions(EncodedResource encodedResource) throws BeanDefinitionStoreException {
.......
try {
//這里通過Resource得到InputStream的IO流
InputStream inputStream = encodedResource.getResource().getInputStream();
try {
//從InputStream中得到XML的解析源
InputSource inputSource = new InputSource(inputStream);
if (encodedResource.getEncoding() != null) {
inputSource.setEncoding(encodedResource.getEncoding());
}
//這里是具體的解析和注冊過程
return doLoadBeanDefinitions(inputSource, encodedResource.getResource());
}
finally {
//關(guān)閉從Resource中得到的IO流
inputStream.close();
}
}
.........
}
protected int doLoadBeanDefinitions(InputSource inputSource, Resource resource)
throws BeanDefinitionStoreException {
try {
int validationMode = getValidationModeForResource(resource);
//通過解析得到DOM,然后完成bean在IOC容器中的注冊
Document doc = this.documentLoader.loadDocument(
inputSource, this.entityResolver, this.errorHandler, validationMode, this.namespaceAware);
return registerBeanDefinitions(doc, resource);
}
.......
}
我們看到先把定義文件解析為DOM對象,然后進(jìn)行具體的注冊過程:
- public int registerBeanDefinitions(Document doc, Resource resource) throws BeanDefinitionStoreException {
-
- if (this.parserClass != null) {
- XmlBeanDefinitionParser parser =
- (XmlBeanDefinitionParser) BeanUtils.instantiateClass(this.parserClass);
- return parser.registerBeanDefinitions(this, doc, resource);
- }
-
- BeanDefinitionDocumentReader documentReader = createBeanDefinitionDocumentReader();
- int countBefore = getBeanFactory().getBeanDefinitionCount();
- documentReader.registerBeanDefinitions(doc, createReaderContext(resource));
- return getBeanFactory().getBeanDefinitionCount() - countBefore;
- }
public int registerBeanDefinitions(Document doc, Resource resource) throws BeanDefinitionStoreException {
// 這里定義解析器,使用XmlBeanDefinitionParser來解析xml方式的bean定義文件 - 現(xiàn)在的版本不用這個解析器了,使用的是XmlBeanDefinitionReader
if (this.parserClass != null) {
XmlBeanDefinitionParser parser =
(XmlBeanDefinitionParser) BeanUtils.instantiateClass(this.parserClass);
return parser.registerBeanDefinitions(this, doc, resource);
}
// 具體的注冊過程,首先得到XmlBeanDefinitionReader,來處理xml的bean定義文件
BeanDefinitionDocumentReader documentReader = createBeanDefinitionDocumentReader();
int countBefore = getBeanFactory().getBeanDefinitionCount();
documentReader.registerBeanDefinitions(doc, createReaderContext(resource));
return getBeanFactory().getBeanDefinitionCount() - countBefore;
}
具體的在BeanDefinitionDocumentReader中完成對,下面是一個簡要的注冊過程來完成bean定義文件的解析和IOC容器中bean的初始化
- public void registerBeanDefinitions(Document doc, XmlReaderContext readerContext) {
- this.readerContext = readerContext;
-
- logger.debug("Loading bean definitions");
- Element root = doc.getDocumentElement();
-
- BeanDefinitionParserDelegate delegate = createHelper(readerContext, root);
-
- preProcessXml(root);
- parseBeanDefinitions(root, delegate);
- postProcessXml(root);
- }
-
- protected void parseBeanDefinitions(Element root, BeanDefinitionParserDelegate delegate) {
- if (delegate.isDefaultNamespace(root.getNamespaceURI())) {
-
- NodeList nl = root.getChildNodes();
-
-
- for (int i = 0; i < nl.getLength(); i++) {
- Node node = nl.item(i);
- if (node instanceof Element) {
- Element ele = (Element) node;
- String namespaceUri = ele.getNamespaceURI();
- if (delegate.isDefaultNamespace(namespaceUri)) {
-
- parseDefaultElement(ele, delegate);
- }
- else {
- delegate.parseCustomElement(ele);
- }
- }
- }
- } else {
- delegate.parseCustomElement(root);
- }
- }
-
- private void parseDefaultElement(Element ele, BeanDefinitionParserDelegate delegate) {
-
- if (DomUtils.nodeNameEquals(ele, IMPORT_ELEMENT)) {
- importBeanDefinitionResource(ele);
- }
- else if (DomUtils.nodeNameEquals(ele, ALIAS_ELEMENT)) {
- String name = ele.getAttribute(NAME_ATTRIBUTE);
- String alias = ele.getAttribute(ALIAS_ATTRIBUTE);
- getReaderContext().getReader().getBeanFactory().registerAlias(name, alias);
- getReaderContext().fireAliasRegistered(name, alias, extractSource(ele));
- }
-
- else if (DomUtils.nodeNameEquals(ele, BEAN_ELEMENT)) {
-
-
- BeanDefinitionHolder bdHolder = delegate.parseBeanDefinitionElement(ele);
- if (bdHolder != null) {
- bdHolder = delegate.decorateBeanDefinitionIfRequired(ele, bdHolder);
-
- BeanDefinitionReaderUtils.registerBeanDefinition(bdHolder, getReaderContext().getRegistry());
-
-
- getReaderContext().fireComponentRegistered(new BeanComponentDefinition(bdHolder));
- }
- }
- }
public void registerBeanDefinitions(Document doc, XmlReaderContext readerContext) {
this.readerContext = readerContext;
logger.debug("Loading bean definitions");
Element root = doc.getDocumentElement();
BeanDefinitionParserDelegate delegate = createHelper(readerContext, root);
preProcessXml(root);
parseBeanDefinitions(root, delegate);
postProcessXml(root);
}
protected void parseBeanDefinitions(Element root, BeanDefinitionParserDelegate delegate) {
if (delegate.isDefaultNamespace(root.getNamespaceURI())) {
//這里得到xml文件的子節(jié)點(diǎn),比如各個bean節(jié)點(diǎn)
NodeList nl = root.getChildNodes();
//這里對每個節(jié)點(diǎn)進(jìn)行分析處理
for (int i = 0; i < nl.getLength(); i++) {
Node node = nl.item(i);
if (node instanceof Element) {
Element ele = (Element) node;
String namespaceUri = ele.getNamespaceURI();
if (delegate.isDefaultNamespace(namespaceUri)) {
//這里是解析過程的調(diào)用,對缺省的元素進(jìn)行分析比如bean元素
parseDefaultElement(ele, delegate);
}
else {
delegate.parseCustomElement(ele);
}
}
}
} else {
delegate.parseCustomElement(root);
}
}
private void parseDefaultElement(Element ele, BeanDefinitionParserDelegate delegate) {
//這里對元素Import進(jìn)行處理
if (DomUtils.nodeNameEquals(ele, IMPORT_ELEMENT)) {
importBeanDefinitionResource(ele);
}
else if (DomUtils.nodeNameEquals(ele, ALIAS_ELEMENT)) {
String name = ele.getAttribute(NAME_ATTRIBUTE);
String alias = ele.getAttribute(ALIAS_ATTRIBUTE);
getReaderContext().getReader().getBeanFactory().registerAlias(name, alias);
getReaderContext().fireAliasRegistered(name, alias, extractSource(ele));
}
//這里對我們最熟悉的bean元素進(jìn)行處理
else if (DomUtils.nodeNameEquals(ele, BEAN_ELEMENT)) {
//委托給BeanDefinitionParserDelegate來完成對bean元素的處理,這個類包含了具體的bean解析的過程。
// 把解析bean文件得到的信息放到BeanDefinition里,他是bean信息的主要載體,也是IOC容器的管理對象。
BeanDefinitionHolder bdHolder = delegate.parseBeanDefinitionElement(ele);
if (bdHolder != null) {
bdHolder = delegate.decorateBeanDefinitionIfRequired(ele, bdHolder);
// 這里是向IOC容器注冊,實際上是放到IOC容器的一個map里
BeanDefinitionReaderUtils.registerBeanDefinition(bdHolder, getReaderContext().getRegistry());
// 這里向IOC容器發(fā)送事件,表示解析和注冊完成。
getReaderContext().fireComponentRegistered(new BeanComponentDefinition(bdHolder));
}
}
}
我們看到在parseBeanDefinition中對具體bean元素的解析式交給BeanDefinitionParserDelegate來完成的,下面我們看看解析完的bean是怎樣在IOC容器中注冊的:
在BeanDefinitionReaderUtils調(diào)用的是:
- public static void registerBeanDefinition(
- BeanDefinitionHolder bdHolder, BeanDefinitionRegistry beanFactory) throws BeansException {
-
-
- String beanName = bdHolder.getBeanName();
-
- beanFactory.registerBeanDefinition(beanName, bdHolder.getBeanDefinition());
-
-
- String[] aliases = bdHolder.getAliases();
- if (aliases != null) {
- for (int i = 0; i < aliases.length; i++) {
- beanFactory.registerAlias(beanName, aliases[i]);
- }
- }
- }
public static void registerBeanDefinition(
BeanDefinitionHolder bdHolder, BeanDefinitionRegistry beanFactory) throws BeansException {
// 這里得到需要注冊bean的名字;
String beanName = bdHolder.getBeanName();
//這是調(diào)用IOC來注冊的bean的過程,需要得到BeanDefinition
beanFactory.registerBeanDefinition(beanName, bdHolder.getBeanDefinition());
// 別名也是可以通過IOC容器和bean聯(lián)系起來的進(jìn)行注冊
String[] aliases = bdHolder.getAliases();
if (aliases != null) {
for (int i = 0; i < aliases.length; i++) {
beanFactory.registerAlias(beanName, aliases[i]);
}
}
}
我們看看XmlBeanFactory中的注冊實現(xiàn):
-
-
-
-
- public void registerBeanDefinition(String beanName, BeanDefinition beanDefinition)
- throws BeanDefinitionStoreException {
-
- .....
-
- Object oldBeanDefinition = this.beanDefinitionMap.get(beanName);
- if (oldBeanDefinition != null) {
- if (!this.allowBeanDefinitionOverriding) {
- ...........
- }
- else {
-
- this.beanDefinitionNames.add(beanName);
- }
-
- this.beanDefinitionMap.put(beanName, beanDefinition);
- removeSingleton(beanName);
- }
//---------------------------------------------------------------------
// 這里是IOC容器對BeanDefinitionRegistry接口的實現(xiàn)
//---------------------------------------------------------------------
public void registerBeanDefinition(String beanName, BeanDefinition beanDefinition)
throws BeanDefinitionStoreException {
.....//這里省略了對BeanDefinition的驗證過程
//先看看在容器里是不是已經(jīng)有了同名的bean,如果有拋出異常。
Object oldBeanDefinition = this.beanDefinitionMap.get(beanName);
if (oldBeanDefinition != null) {
if (!this.allowBeanDefinitionOverriding) {
...........
}
else {
//把bean的名字加到IOC容器中去
this.beanDefinitionNames.add(beanName);
}
//這里把bean的名字和Bean定義聯(lián)系起來放到一個HashMap中去,IOC容器通過這個Map來維護(hù)容器里的Bean定義信息。
this.beanDefinitionMap.put(beanName, beanDefinition);
removeSingleton(beanName);
}
這樣就完成了Bean定義在IOC容器中的注冊,就可被IOC容器進(jìn)行管理和使用了。
從上面的代碼來看,我們總結(jié)一下IOC容器初始化的基本步驟:
* 初始化的入口在容器實現(xiàn)中的refresh()調(diào)用來完成
* 對bean 定義載入IOC容器使用的方法是loadBeanDefinition,其中的大致過程如下:通過ResourceLoader來完成資源文件位置的定位,DefaultResourceLoader是默認(rèn)的實現(xiàn),同時上下文本身就給出了ResourceLoader的實現(xiàn),可以從類路徑,文件系統(tǒng), URL等方式來定為資源位置。如果是XmlBeanFactory作為IOC容器,那么需要為它指定bean定義的資源,也就是說bean定義文件時通過抽象成Resource來被IOC容器處理的,容器通過BeanDefinitionReader來完成定義信息的解析和Bean信息的注冊,往往使用的是XmlBeanDefinitionReader來解析bean的xml定義文件 - 實際的處理過程是委托給BeanDefinitionParserDelegate來完成的,從而得到bean的定義信息,這些信息在Spring中使用BeanDefinition對象來表示 - 這個名字可以讓我們想到loadBeanDefinition,RegisterBeanDefinition這些相關(guān)的方法 - 他們都是為處理BeanDefinitin服務(wù)的,IoC容器解析得到BeanDefinition以后,需要把它在IOC容器中注冊,這由IOC實現(xiàn) BeanDefinitionRegistry接口來實現(xiàn)。注冊過程就是在IOC容器內(nèi)部維護(hù)的一個HashMap來保存得到的 BeanDefinition的過程。這個HashMap是IoC容器持有bean信息的場所,以后對bean的操作都是圍繞這個HashMap來實現(xiàn)的。
* 然后我們就可以通過BeanFactory和ApplicationContext來享受到Spring IOC的服務(wù)了.
在使用IOC容器的時候,我們注意到除了少量粘合代碼,絕大多數(shù)以正確IoC風(fēng)格編寫的應(yīng)用程序代碼完全不用關(guān)心如何到達(dá)工廠,因為容器將把這些對象與容器管理的其他對象鉤在一起。基本的策略是把工廠放到已知的地方,最好是放在對預(yù)期使用的上下文有意義的地方,以及代碼將實際需要訪問工廠的地方。 Spring本身提供了對聲明式載入web應(yīng)用程序用法的應(yīng)用程序上下文,并將其存儲在ServletContext中的框架實現(xiàn)。具體可以參見以后的文章。
在使用Spring IOC容器的時候我們還需要區(qū)別兩個概念:
Beanfactory 和Factory bean,其中BeanFactory指的是IOC容器的編程抽象,比如ApplicationContext, XmlBeanFactory等,這些都是IOC容器的具體表現(xiàn),需要使用什么樣的容器由客戶決定但Spring為我們提供了豐富的選擇。而 FactoryBean只是一個可以在IOC容器中被管理的一個bean,是對各種處理過程和資源使用的抽象,Factory bean在需要時產(chǎn)生另一個對象,而不返回FactoryBean本省,我們可以把它看成是一個抽象工廠,對它的調(diào)用返回的是工廠生產(chǎn)的產(chǎn)品。所有的 Factory bean都實現(xiàn)特殊的org.springframework.beans.factory.FactoryBean接口,當(dāng)使用容器中factory bean的時候,該容器不會返回factory bean本身,而是返回其生成的對象。Spring包括了大部分的通用資源和服務(wù)訪問抽象的Factory bean的實現(xiàn),其中包括:
對JNDI查詢的處理,對代理對象的處理,對事務(wù)性代理的處理,對RMI代理的處理等,這些我們都可以看成是具體的工廠,看成是SPRING為我們建立好的工廠。也就是說Spring通過使用抽象工廠模式為我們準(zhǔn)備了一系列工廠來生產(chǎn)一些特定的對象,免除我們手工重復(fù)的工作,我們要使用時只需要在IOC容器里配置好就能很方便的使用了。
現(xiàn)在我們來看看在Spring的事件機(jī)制,Spring中有3個標(biāo)準(zhǔn)事件,ContextRefreshEvent, ContextCloseEvent,RequestHandledEvent他們通過ApplicationEvent接口,同樣的如果需要自定義時間也只需要實現(xiàn)ApplicationEvent接口,參照ContextCloseEvent的實現(xiàn)可以定制自己的事件實現(xiàn):
- public class ContextClosedEvent extends ApplicationEvent {
-
- public ContextClosedEvent(ApplicationContext source) {
- super(source);
- }
-
- public ApplicationContext getApplicationContext() {
- return (ApplicationContext) getSource();
- }
- }
public class ContextClosedEvent extends ApplicationEvent {
public ContextClosedEvent(ApplicationContext source) {
super(source);
}
public ApplicationContext getApplicationContext() {
return (ApplicationContext) getSource();
}
}
可以通過顯現(xiàn)ApplicationEventPublishAware接口,將事件發(fā)布器耦合到ApplicationContext這樣可以使用 ApplicationContext框架來傳遞和消費(fèi)消息,然后在ApplicationContext中配置好bean就可以了,在消費(fèi)消息的過程中,接受者通過實現(xiàn)ApplicationListener接收消息。
比如可以直接使用Spring的ScheduleTimerTask和TimerFactoryBean作為定時器定時產(chǎn)生消息,具體可以參見《Spring框架高級編程》。
TimerFactoryBean是一個工廠bean,對其中的ScheduleTimerTask進(jìn)行處理后輸出,參考ScheduleTimerTask的實現(xiàn)發(fā)現(xiàn)它最后調(diào)用的是jre的TimerTask:
- public void setRunnable(Runnable timerTask) {
- this.timerTask = new DelegatingTimerTask(timerTask);
- }
public void setRunnable(Runnable timerTask) {
this.timerTask = new DelegatingTimerTask(timerTask);
}
在書中給出了一個定時發(fā)送消息的例子,當(dāng)然可以可以通過定時器作其他的動作,有兩種方法:
1.定義MethodInvokingTimerTaskFactoryBean定義要執(zhí)行的特定bean的特定方法,對需要做什么進(jìn)行封裝定義;
2.定義TimerTask類,通過extends TimerTask來得到,同時對需要做什么進(jìn)行自定義
然后需要定義具體的定時器參數(shù),通過配置ScheduledTimerTask中的參數(shù)和timerTask來完成,以下是它需要定義的具體屬性,timerTask是在前面已經(jīng)定義好的bean
- private TimerTask timerTask;
-
- private long delay = 0;
-
- private long period = 0;
-
- private boolean fixedRate = false;
private TimerTask timerTask;
private long delay = 0;
private long period = 0;
private boolean fixedRate = false;
最后,需要在ApplicationContext中注冊,需要把ScheduledTimerTask配置到FactoryBean - TimerFactoryBean,這樣就由IOC容器來管理定時器了。參照
TimerFactoryBean的屬性,可以定制一組定時器。
- public class TimerFactoryBean implements FactoryBean, InitializingBean, DisposableBean {
-
- protected final Log logger = LogFactory.getLog(getClass());
-
- private ScheduledTimerTask[] scheduledTimerTasks;
-
- private boolean daemon = false;
-
- private Timer timer;
-
- ...........
- }
public class TimerFactoryBean implements FactoryBean, InitializingBean, DisposableBean {
protected final Log logger = LogFactory.getLog(getClass());
private ScheduledTimerTask[] scheduledTimerTasks;
private boolean daemon = false;
private Timer timer;
...........
}
如果要發(fā)送時間我們只需要在定義好的ScheduledTimerTasks中publish定義好的事件就可以了。具體可以參考書中例子的實現(xiàn),這里只是結(jié)合FactoryBean的原理做一些解釋。如果結(jié)合事件和定時器機(jī)制,我們可以很方便的實現(xiàn)heartbeat(看門狗),書中給出了這個例子,這個例子實際上結(jié)合了Spring事件和定時機(jī)制的使用兩個方面的知識 - 當(dāng)然了還有IOC容器的知識(任何Spring應(yīng)用我想都逃不掉IOC的魔爪:)