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