---
title: "Spring源代码解析(一）：IOC容器"
author: "yiliner"
date: "2009-10-13T09:49:44Z"
tags: []
slug: "spring-ioc"
draft: false
lastmod: "2009-10-13T09:49:44Z"
id: 486702
url: "https://yiliner.iteye.com/blog/486702"
---

相关文章: [](http://yiliner.iteye.com/admin/blogs/ "关闭") 

- [关于spring ioc容器的问题](http://www.iteye.com/topic/95577 "关于spring ioc容器的问题")
- [spring源码分析-XmlBeanFactory导读](http://www.iteye.com/topic/75171 "spring源码分析-XmlBeanFactory导读")
- [关于spring 2.0自定义xml 标记 （二 如何实现）](http://www.iteye.com/topic/30964 "关于spring 2.0自定义xml 标记 （二 如何实现）")

推荐圈子: [Java淄博圈子](http://zibo.group.iteye.com/)  
[更多相关推荐](http://yiliner.iteye.com/wiki/topic/86339)

&lt;script type="text/javascript"&gt;&lt;/script&gt; 在认真学习Rod.Johnson的三部曲之一：&lt;&lt;Professional Java Development with the spring framework&gt;&gt;,顺便也看了看源代码想知道个究竟，抛砖引玉，有兴趣的同志一起讨论研究吧！  
以下内容引自博客：[http://jiwenke-spring.blogspot.com/](http://jiwenke-spring.blogspot.com/),欢迎指导：）  
在Spring中，IOC容器的重要地位我们就不多说了，对于Spring的使用者而言，IOC容器实际上是什么呢？我们可以说BeanFactory就是我们看到的IoC容器，当然了Spring为我们准备了许多种IoC容器来使用，这样可以方便我们从不同的层面，不同的资源位置，不同的形式的定义信息来建立我们需要的IoC容器。  
在Spring中，最基本的IOC容器接口是BeanFactory - 这个接口为具体的IOC容器的实现作了最基本的功能规定 - 不管怎么着，作为IOC容器，这些接口你必须要满足应用程序的最基本要求：

Java代码 [![复制代码](http://www.iteye.com/images/icon_copy.gif)](http://www.iteye.com/topic/86339 "复制代码")

01. public interface BeanFactory {
02. //这里是对FactoryBean的转义定义，因为如果使用bean的名字检索FactoryBean得到的对象是工厂生成的对象，
03. //如果需要得到工厂本身，需要转义
04. String FACTORY\_BEAN\_PREFIX = "&";
05. //这里根据bean的名字，在IOC容器中得到bean实例，这个IOC容器就是一个大的抽象工厂。
06. Object getBean(String name) throws BeansException;
07. //这里根据bean的名字和Class类型来得到bean实例，和上面的方法不同在于它会抛出异常：如果根据名字取得的bean实例的Class类型和需要的不同的话。
08. Object getBean(String name, Class requiredType) throws BeansException;
09. //这里提供对bean的检索，看看是否在IOC容器有这个名字的bean
10. boolean containsBean(String name);
11. //这里根据bean名字得到bean实例，并同时判断这个bean是不是单件
12. boolean isSingleton(String name) throws NoSuchBeanDefinitionException;
13. //这里对得到bean实例的Class类型
14. Class getType(String name) throws NoSuchBeanDefinitionException;
15. //这里得到bean的别名，如果根据别名检索，那么其原名也会被检索出来
16. String\[] getAliases(String name);
17. }

```
public interface BeanFactory {

    //这里是对FactoryBean的转义定义，因为如果使用bean的名字检索FactoryBean得到的对象是工厂生成的对象，
    //如果需要得到工厂本身，需要转义       
    String FACTORY_BEAN_PREFIX = "&";


    //这里根据bean的名字，在IOC容器中得到bean实例，这个IOC容器就是一个大的抽象工厂。
    Object getBean(String name) throws BeansException;

    //这里根据bean的名字和Class类型来得到bean实例，和上面的方法不同在于它会抛出异常：如果根据名字取得的bean实例的Class类型和需要的不同的话。
    Object getBean(String name, Class requiredType) throws BeansException;

    //这里提供对bean的检索，看看是否在IOC容器有这个名字的bean
    boolean containsBean(String name);

    //这里根据bean名字得到bean实例，并同时判断这个bean是不是单件
    boolean isSingleton(String name) throws NoSuchBeanDefinitionException;

    //这里对得到bean实例的Class类型
    Class getType(String name) throws NoSuchBeanDefinitionException;

    //这里得到bean的别名，如果根据别名检索，那么其原名也会被检索出来
    String[] getAliases(String name);

}
```

在BeanFactory里只对IOC容器的基本行为作了定义，根本不关心你的bean是怎样定义怎样加载的 - 就像我们只关心从这个工厂里我们得到到什么产品对象，至于工厂是怎么生产这些对象的，这个基本的接口不关心这些。如果要关心工厂是怎样产生对象的，应用程序需要使用具体的IOC容器实现- 当然你可以自己根据这个BeanFactory来实现自己的IOC容器，但这个没有必要，因为Spring已经为我们准备好了一系列工厂来让我们使用。比如XmlBeanFactory就是针对最基础的BeanFactory的IOC容器的实现 - 这个实现使用xml来定义IOC容器中的bean。  
Spring提供了一个BeanFactory的基本实现，XmlBeanFactory同样的通过使用模板模式来得到对IOC容器的抽象- AbstractBeanFactory,DefaultListableBeanFactory这些抽象类为其提供模板服务。其中通过resource 接口来抽象bean定义数据，对Xml定义文件的解析通过委托给XmlBeanDefinitionReader来完成。下面我们根据书上的例子，简单的演示IOC容器的创建过程：

Java代码 [![复制代码](http://www.iteye.com/images/icon_copy.gif)](http://www.iteye.com/topic/86339 "复制代码")

1. ClassPathResource res = new ClassPathResource("beans.xml");
2. DefaultListableBeanFactory factory = new DefaultListableBeanFactory();
3. XmlBeanDefinitionReader reader = new XmlBeanDefinitionReader(factory);
4. reader.loadBeanDefinitions(res);

```
    ClassPathResource res = new ClassPathResource("beans.xml");
    DefaultListableBeanFactory factory = new DefaultListableBeanFactory();
    XmlBeanDefinitionReader reader = new XmlBeanDefinitionReader(factory);
    reader.loadBeanDefinitions(res);
```

这些代码演示了以下几个步骤：

   1. 创建IOC配置文件的抽象资源  
   2. 创建一个BeanFactory  
   3. 把读取配置信息的BeanDefinitionReader,这里是XmlBeanDefinitionReader配置给BeanFactory  
   4. 从定义好的资源位置读入配置信息，具体的解析过程由XmlBeanDefinitionReader来完成，这样完成整个载入bean定义的过程。我们的IoC容器就建立起来了。在BeanFactory的源代码中我们可以看到：

Java代码 [![复制代码](http://www.iteye.com/images/icon_copy.gif)](http://www.iteye.com/topic/86339 "复制代码")

01. public class XmlBeanFactory extends DefaultListableBeanFactory {
02. //这里为容器定义了一个默认使用的bean定义读取器
03. private final XmlBeanDefinitionReader reader = new XmlBeanDefinitionReader(this);
04. public XmlBeanFactory(Resource resource) throws BeansException {
05. this(resource, null);
06. }
07. //在初始化函数中使用读取器来对资源进行读取，得到bean定义信息。
08. public XmlBeanFactory(Resource resource, BeanFactory parentBeanFactory) throws BeansException {
09. super(parentBeanFactory);
10. this.reader.loadBeanDefinitions(resource);
11. }

```
public class XmlBeanFactory extends DefaultListableBeanFactory {
    //这里为容器定义了一个默认使用的bean定义读取器
    private final XmlBeanDefinitionReader reader = new XmlBeanDefinitionReader(this);
    public XmlBeanFactory(Resource resource) throws BeansException {
        this(resource, null);
    }
    //在初始化函数中使用读取器来对资源进行读取，得到bean定义信息。
    public XmlBeanFactory(Resource resource, BeanFactory parentBeanFactory) throws BeansException {
        super(parentBeanFactory);
        this.reader.loadBeanDefinitions(resource);
    }
```

我们在后面会看到读取器读取资源和注册bean定义信息的整个过程，基本上是和上下文的处理是一样的，从这里我们可以看到上下文和 XmlBeanFactory这两种IOC容器的区别，BeanFactory往往不具备对资源定义的能力，而上下文可以自己完成资源定义，从这个角度上看上下文更好用一些。  
仔细分析Spring BeanFactory的结构，我们来看看在BeanFactory基础上扩展出的ApplicationContext - 我们最常使用的上下文。除了具备BeanFactory的全部能力，上下文为应用程序又增添了许多便利：

    * 可以支持不同的信息源，我们看到ApplicationContext扩展了MessageSource  
    * 访问资源 , 体现在对ResourceLoader和Resource的支持上面，这样我们可以从不同地方得到bean定义资源  
    * 支持应用事件，继承了接口ApplicationEventPublisher,这样在上下文中引入了事件机制而BeanFactory是没有的。

ApplicationContext允许上下文嵌套 - 通过保持父上下文可以维持一个上下文体系 - 这个体系我们在以后对Web容器中的上下文环境的分析中可以清楚地看到。对于bean的查找可以在这个上下文体系中发生，首先检查当前上下文，其次是父上下文，逐级向上，这样为不同的Spring应用提供了一个共享的bean定义环境。这个我们在分析Web容器中的上下文环境时也能看到。  
ApplicationContext提供IoC容器的主要接口，在其体系中有许多抽象子类比如AbstractApplicationContext为具体的BeanFactory的实现，比如FileSystemXmlApplicationContext和 ClassPathXmlApplicationContext提供上下文的模板，使得他们只需要关心具体的资源定位问题。当应用程序代码实例化 FileSystemXmlApplicationContext的时候，得到IoC容器的一种具体表现 - ApplicationContext，从而应用程序通过ApplicationContext来管理对bean的操作。  
BeanFactory 是一个接口，在实际应用中我们一般使用ApplicationContext来使用IOC容器，它们也是IOC容器展现给应用开发者的使用接口。对应用程序开发者来说，可以认为BeanFactory和ApplicationFactory在不同的使用层面上代表了SPRING提供的IOC容器服务。  
下面我们具体看看通过FileSystemXmlApplicationContext是怎样建立起IOC容器的, 显而易见我们可以通过new来得到IoC容器：

Java代码 [![复制代码](http://www.iteye.com/images/icon_copy.gif)](http://www.iteye.com/topic/86339 "复制代码")

1. ApplicationContext = new FileSystemXmlApplicationContext(xmlPath);

```
   ApplicationContext = new FileSystemXmlApplicationContext(xmlPath);
```

调用的是它初始化代码：

Java代码 [![复制代码](http://www.iteye.com/images/icon_copy.gif)](http://www.iteye.com/topic/86339 "复制代码")

1. public FileSystemXmlApplicationContext(String\[] configLocations, boolean refresh, ApplicationContext parent)
2. throws BeansException {
3. super(parent);
4. this.configLocations = configLocations;
5. if (refresh) {
6. //这里是IoC容器的初始化过程，其初始化过程的大致步骤由AbstractApplicationContext来定义
7. refresh();
8. }
9. }

```
    public FileSystemXmlApplicationContext(String[] configLocations, boolean refresh, ApplicationContext parent)
            throws BeansException {
        super(parent);
        this.configLocations = configLocations;
        if (refresh) {
          　//这里是IoC容器的初始化过程，其初始化过程的大致步骤由AbstractApplicationContext来定义
            refresh();
        }
    }
```

refresh的模板在AbstractApplicationContext:

Java代码 [![复制代码](http://www.iteye.com/images/icon_copy.gif)](http://www.iteye.com/topic/86339 "复制代码")

1. public void refresh() throws BeansException, IllegalStateException {
2. synchronized (this.startupShutdownMonitor) {
3. synchronized (this.activeMonitor) {
4. this.active = true;
5. }
6. // 这里需要子类来协助完成资源位置定义,bean载入和向IOC容器注册的过程
7. refreshBeanFactory();
8. ............
9. }

```
    public void refresh() throws BeansException, IllegalStateException {
        synchronized (this.startupShutdownMonitor) {
            synchronized (this.activeMonitor) {
                this.active = true;
            }

            // 这里需要子类来协助完成资源位置定义,bean载入和向IOC容器注册的过程
            refreshBeanFactory();
            ............
     }
```

这个方法包含了整个BeanFactory初始化的过程，对于特定的FileSystemXmlBeanFactory,我们看到定位资源位置由refreshBeanFactory()来实现：  
在AbstractXmlApplicationContext中定义了对资源的读取过程，默认由XmlBeanDefinitionReader来读取：

Java代码 [![复制代码](http://www.iteye.com/images/icon_copy.gif)](http://www.iteye.com/topic/86339 "复制代码")

01. protected void loadBeanDefinitions(DefaultListableBeanFactory beanFactory) throws IOException {
02. // 这里使用XMLBeanDefinitionReader来载入bean定义信息的XML文件
03. XmlBeanDefinitionReader beanDefinitionReader = new XmlBeanDefinitionReader(beanFactory);
04. //这里配置reader的环境，其中ResourceLoader是我们用来定位bean定义信息资源位置的
05. ///因为上下文本身实现了ResourceLoader接口，所以可以直接把上下文作为ResourceLoader传递给XmlBeanDefinitionReader
06. beanDefinitionReader.setResourceLoader(this);
07. beanDefinitionReader.setEntityResolver(new ResourceEntityResolver(this));
08. initBeanDefinitionReader(beanDefinitionReader);
09. //这里转到定义好的XmlBeanDefinitionReader中对载入bean信息进行处理
10. loadBeanDefinitions(beanDefinitionReader);
11. }

```
    protected void loadBeanDefinitions(DefaultListableBeanFactory beanFactory) throws IOException {
        // 这里使用XMLBeanDefinitionReader来载入bean定义信息的XML文件
        XmlBeanDefinitionReader beanDefinitionReader = new XmlBeanDefinitionReader(beanFactory);

        //这里配置reader的环境，其中ResourceLoader是我们用来定位bean定义信息资源位置的
        ///因为上下文本身实现了ResourceLoader接口，所以可以直接把上下文作为ResourceLoader传递给XmlBeanDefinitionReader
        beanDefinitionReader.setResourceLoader(this);
        beanDefinitionReader.setEntityResolver(new ResourceEntityResolver(this));

        initBeanDefinitionReader(beanDefinitionReader);
        //这里转到定义好的XmlBeanDefinitionReader中对载入bean信息进行处理
        loadBeanDefinitions(beanDefinitionReader);
    }
```

转到beanDefinitionReader中进行处理：

Java代码 [![复制代码](http://www.iteye.com/images/icon_copy.gif)](http://www.iteye.com/topic/86339 "复制代码")

01. protected void loadBeanDefinitions(XmlBeanDefinitionReader reader) throws BeansException, IOException {
02. Resource\[] configResources = getConfigResources();
03. if (configResources != null) {
04. //调用XmlBeanDefinitionReader来载入bean定义信息。
05. reader.loadBeanDefinitions(configResources);
06. }
07. String\[] configLocations = getConfigLocations();
08. if (configLocations != null) {
09. reader.loadBeanDefinitions(configLocations);
10. }
11. }

```
    protected void loadBeanDefinitions(XmlBeanDefinitionReader reader) throws BeansException, IOException {
        Resource[] configResources = getConfigResources();
        if (configResources != null) {
            //调用XmlBeanDefinitionReader来载入bean定义信息。
            reader.loadBeanDefinitions(configResources);
        }
        String[] configLocations = getConfigLocations();
        if (configLocations != null) {
            reader.loadBeanDefinitions(configLocations);
        }
    }
```

而在作为其抽象父类的AbstractBeanDefinitionReader中来定义载入过程：

Java代码 [![复制代码](http://www.iteye.com/images/icon_copy.gif)](http://www.iteye.com/topic/86339 "复制代码")

01. public int loadBeanDefinitions(String location) throws BeanDefinitionStoreException {
02. //这里得到当前定义的ResourceLoader,默认的我们使用DefaultResourceLoader
03. ResourceLoader resourceLoader = getResourceLoader();
04. .........//如果没有找到我们需要的ResourceLoader，直接抛出异常
05. if (resourceLoader instanceof ResourcePatternResolver) {
06. // 这里处理我们在定义位置时使用的各种pattern,需要ResourcePatternResolver来完成
07. try {
08. Resource\[] resources = ((ResourcePatternResolver) resourceLoader).getResources(location);
09. int loadCount = loadBeanDefinitions(resources);
10. return loadCount;
11. }
12. ........
13. }
14. else {
15. // 这里通过ResourceLoader来完成位置定位
16. Resource resource = resourceLoader.getResource(location);
17. // 这里已经把一个位置定义转化为Resource接口，可以供XmlBeanDefinitionReader来使用了
18. int loadCount = loadBeanDefinitions(resource);
19. return loadCount;
20. }
21. }

```
    public int loadBeanDefinitions(String location) throws BeanDefinitionStoreException {
     //这里得到当前定义的ResourceLoader,默认的我们使用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);
            // 这里已经把一个位置定义转化为Resource接口，可以供XmlBeanDefinitionReader来使用了
            int loadCount = loadBeanDefinitions(resource);
            return loadCount;
        }
    }
```

当我们通过ResourceLoader来载入资源，别忘了了我们的GenericApplicationContext也实现了ResourceLoader接口：

Java代码 [![复制代码](http://www.iteye.com/images/icon_copy.gif)](http://www.iteye.com/topic/86339 "复制代码")

01. public class GenericApplicationContext extends AbstractApplicationContext implements BeanDefinitionRegistry {
02. public Resource getResource(String location) {
03. //这里调用当前的loader也就是DefaultResourceLoader来完成载入
04. if (this.resourceLoader != null) {
05. return this.resourceLoader.getResource(location);
06. }
07. return super.getResource(location);
08. }
09. .......
10. }

```
    public class GenericApplicationContext extends AbstractApplicationContext implements BeanDefinitionRegistry {
        public Resource getResource(String location) {
            //这里调用当前的loader也就是DefaultResourceLoader来完成载入
            if (this.resourceLoader != null) {
                return this.resourceLoader.getResource(location);
            }
            return super.getResource(location);
        }
    .......
    }
```

而我们的FileSystemXmlApplicationContext就是一个DefaultResourceLoader - GenericApplicationContext()通过DefaultResourceLoader:

Java代码 [![复制代码](http://www.iteye.com/images/icon_copy.gif)](http://www.iteye.com/topic/86339 "复制代码")

01. public Resource getResource(String location) {
02. //如果是类路径的方式，那需要使用ClassPathResource来得到bean文件的资源对象
03. if (location.startsWith(CLASSPATH\_URL\_PREFIX)) {
04. return new ClassPathResource(location.substring(CLASSPATH\_URL\_PREFIX.length()), getClassLoader());
05. }
06. else {
07. try {
08. // 如果是URL方式，使用UrlResource作为bean文件的资源对象
09. URL url = new URL(location);
10. return new UrlResource(url);
11. }
12. catch (MalformedURLException ex) {
13. // 如果都不是，那我们只能委托给子类由子类来决定使用什么样的资源对象了
14. return getResourceByPath(location);
15. }
16. }
17. }

```
    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的实现类，他实现了以下的接口：

Java代码 [![复制代码](http://www.iteye.com/images/icon_copy.gif)](http://www.iteye.com/topic/86339 "复制代码")

1. protected Resource getResourceByPath(String path) {
2. if (path != null && path.startsWith("/")) {
3. path = path.substring(1);
4. }
5. //这里使用文件系统资源对象来定义bean文件
6. return new FileSystemResource(path);
7. }

```
    protected Resource getResourceByPath(String path) {
        if (path != null && path.startsWith("/")) {
            path = path.substring(1);
        }
        //这里使用文件系统资源对象来定义bean文件
        return new FileSystemResource(path);
    }
```

这样代码就回到了FileSystemXmlApplicationContext中来，他提供了FileSystemResource来完成从文件系统得到配置文件的资源定义。这样，就可以从文件系统路径上对IOC配置文件进行加载 - 当然我们可以按照这个逻辑从任何地方加载，在Spring中我们看到它提供的各种资源抽象，比如ClassPathResource, URLResource,FileSystemResource等来供我们使用。上面我们看到的是定位Resource的一个过程，而这只是加载过程的一部分 - 我们回到AbstractBeanDefinitionReaderz中的loadDefinitions(resource)来看看得到代表bean文件的资源定义以后的载入过程,默认的我们使用XmlBeanDefinitionReader：

Java代码 [![复制代码](http://www.iteye.com/images/icon_copy.gif)](http://www.iteye.com/topic/86339 "复制代码")

01. public int loadBeanDefinitions(EncodedResource encodedResource) throws BeanDefinitionStoreException {
02. .......
03. try {
04. //这里通过Resource得到InputStream的IO流
05. InputStream inputStream = encodedResource.getResource().getInputStream();
06. try {
07. //从InputStream中得到XML的解析源
08. InputSource inputSource = new InputSource(inputStream);
09. if (encodedResource.getEncoding() != null) {
10. inputSource.setEncoding(encodedResource.getEncoding());
11. }
12. //这里是具体的解析和注册过程
13. return doLoadBeanDefinitions(inputSource, encodedResource.getResource());
14. }
15. finally {
16. //关闭从Resource中得到的IO流
17. inputStream.close();
18. }
19. }
20. .........
21. }
22. protected int doLoadBeanDefinitions(InputSource inputSource, Resource resource)
23. throws BeanDefinitionStoreException {
24. try {
25. int validationMode = getValidationModeForResource(resource);
26. //通过解析得到DOM，然后完成bean在IOC容器中的注册
27. Document doc = this.documentLoader.loadDocument(
28. inputSource, this.entityResolver, this.errorHandler, validationMode, this.namespaceAware);
29. return registerBeanDefinitions(doc, resource);
30. }
31. .......
32. }

```
    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 {
                //关闭从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对象，然后进行具体的注册过程：

Java代码 [![复制代码](http://www.iteye.com/images/icon_copy.gif)](http://www.iteye.com/topic/86339 "复制代码")

01. public int registerBeanDefinitions(Document doc, Resource resource) throws BeanDefinitionStoreException {
02. // 这里定义解析器，使用XmlBeanDefinitionParser来解析xml方式的bean定义文件 - 现在的版本不用这个解析器了，使用的是XmlBeanDefinitionReader
03. if (this.parserClass != null) {
04. XmlBeanDefinitionParser parser =
05. (XmlBeanDefinitionParser) BeanUtils.instantiateClass(this.parserClass);
06. return parser.registerBeanDefinitions(this, doc, resource);
07. }
08. // 具体的注册过程,首先得到XmlBeanDefinitionReader,来处理xml的bean定义文件
09. BeanDefinitionDocumentReader documentReader = createBeanDefinitionDocumentReader();
10. int countBefore = getBeanFactory().getBeanDefinitionCount();
11. documentReader.registerBeanDefinitions(doc, createReaderContext(resource));
12. return getBeanFactory().getBeanDefinitionCount() - countBefore;
13. }

```
    public int registerBeanDefinitions(Document doc, Resource resource) throws BeanDefinitionStoreException {
        // 这里定义解析器，使用XmlBeanDefinitionParser来解析xml方式的bean定义文件 - 现在的版本不用这个解析器了，使用的是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的初始化

Java代码 [![复制代码](http://www.iteye.com/images/icon_copy.gif)](http://www.iteye.com/topic/86339 "复制代码")

01. public void registerBeanDefinitions(Document doc, XmlReaderContext readerContext) {
02. this.readerContext = readerContext;
03. logger.debug("Loading bean definitions");
04. Element root = doc.getDocumentElement();
05. BeanDefinitionParserDelegate delegate = createHelper(readerContext, root);
06. preProcessXml(root);
07. parseBeanDefinitions(root, delegate);
08. postProcessXml(root);
09. }
10. protected void parseBeanDefinitions(Element root, BeanDefinitionParserDelegate delegate) {
11. if (delegate.isDefaultNamespace(root.getNamespaceURI())) {
12. //这里得到xml文件的子节点，比如各个bean节点
13. NodeList nl = root.getChildNodes();
14. //这里对每个节点进行分析处理
15. for (int i = 0; i &lt; nl.getLength(); i++) {
16. Node node = nl.item(i);
17. if (node instanceof Element) {
18. Element ele = (Element) node;
19. String namespaceUri = ele.getNamespaceURI();
20. if (delegate.isDefaultNamespace(namespaceUri)) {
21. //这里是解析过程的调用，对缺省的元素进行分析比如bean元素
22. parseDefaultElement(ele, delegate);
23. }
24. else {
25. delegate.parseCustomElement(ele);
26. }
27. }
28. }
29. } else {
30. delegate.parseCustomElement(root);
31. }
32. }
33. private void parseDefaultElement(Element ele, BeanDefinitionParserDelegate delegate) {
34. //这里对元素Import进行处理
35. if (DomUtils.nodeNameEquals(ele, IMPORT\_ELEMENT)) {
36. importBeanDefinitionResource(ele);
37. }
38. else if (DomUtils.nodeNameEquals(ele, ALIAS\_ELEMENT)) {
39. String name = ele.getAttribute(NAME\_ATTRIBUTE);
40. String alias = ele.getAttribute(ALIAS\_ATTRIBUTE);
41. getReaderContext().getReader().getBeanFactory().registerAlias(name, alias);
42. getReaderContext().fireAliasRegistered(name, alias, extractSource(ele));
43. }
44. //这里对我们最熟悉的bean元素进行处理
45. else if (DomUtils.nodeNameEquals(ele, BEAN\_ELEMENT)) {
46. //委托给BeanDefinitionParserDelegate来完成对bean元素的处理，这个类包含了具体的bean解析的过程。
47. // 把解析bean文件得到的信息放到BeanDefinition里，他是bean信息的主要载体，也是IOC容器的管理对象。
48. BeanDefinitionHolder bdHolder = delegate.parseBeanDefinitionElement(ele);
49. if (bdHolder != null) {
50. bdHolder = delegate.decorateBeanDefinitionIfRequired(ele, bdHolder);
51. // 这里是向IOC容器注册，实际上是放到IOC容器的一个map里
52. BeanDefinitionReaderUtils.registerBeanDefinition(bdHolder, getReaderContext().getRegistry());
53. // 这里向IOC容器发送事件，表示解析和注册完成。
54. getReaderContext().fireComponentRegistered(new BeanComponentDefinition(bdHolder));
55. }
56. }
57. }

```
    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文件的子节点，比如各个bean节点         
            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)) {
                        //这里是解析过程的调用，对缺省的元素进行分析比如bean元素
                        parseDefaultElement(ele, delegate);
                    }
                    else {
                        delegate.parseCustomElement(ele);
                    }
                }
            }
        } else {
            delegate.parseCustomElement(root);
        }
    }

    private void parseDefaultElement(Element ele, BeanDefinitionParserDelegate delegate) {
        //这里对元素Import进行处理
        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元素进行处理
        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容器发送事件，表示解析和注册完成。
                getReaderContext().fireComponentRegistered(new BeanComponentDefinition(bdHolder));
            }
        }
    }
```

我们看到在parseBeanDefinition中对具体bean元素的解析式交给BeanDefinitionParserDelegate来完成的，下面我们看看解析完的bean是怎样在IOC容器中注册的：  
在BeanDefinitionReaderUtils调用的是：

Java代码 [![复制代码](http://www.iteye.com/images/icon_copy.gif)](http://www.iteye.com/topic/86339 "复制代码")

01. public static void registerBeanDefinition(
02. BeanDefinitionHolder bdHolder, BeanDefinitionRegistry beanFactory) throws BeansException {
03. // 这里得到需要注册bean的名字；
04. String beanName = bdHolder.getBeanName();
05. //这是调用IOC来注册的bean的过程，需要得到BeanDefinition
06. beanFactory.registerBeanDefinition(beanName, bdHolder.getBeanDefinition());
07. // 别名也是可以通过IOC容器和bean联系起来的进行注册
08. String\[] aliases = bdHolder.getAliases();
09. if (aliases != null) {
10. for (int i = 0; i &lt; aliases.length; i++) {
11. beanFactory.registerAlias(beanName, aliases\[i]);
12. }
13. }
14. }

```
    public static void registerBeanDefinition(
            BeanDefinitionHolder bdHolder, BeanDefinitionRegistry beanFactory) throws BeansException {

        // 这里得到需要注册bean的名字；
        String beanName = bdHolder.getBeanName();
        //这是调用IOC来注册的bean的过程，需要得到BeanDefinition
        beanFactory.registerBeanDefinition(beanName, bdHolder.getBeanDefinition());

        // 别名也是可以通过IOC容器和bean联系起来的进行注册
        String[] aliases = bdHolder.getAliases();
        if (aliases != null) {
            for (int i = 0; i < aliases.length; i++) {
                beanFactory.registerAlias(beanName, aliases[i]);
            }
        }
    }
```

我们看看XmlBeanFactory中的注册实现：

Java代码 [![复制代码](http://www.iteye.com/images/icon_copy.gif)](http://www.iteye.com/topic/86339 "复制代码")

01. //---------------------------------------------------------------------
02. // 这里是IOC容器对BeanDefinitionRegistry接口的实现
03. //---------------------------------------------------------------------
04. public void registerBeanDefinition(String beanName, BeanDefinition beanDefinition)
05. throws BeanDefinitionStoreException {
06. .....//这里省略了对BeanDefinition的验证过程
07. //先看看在容器里是不是已经有了同名的bean,如果有抛出异常。
08. Object oldBeanDefinition = this.beanDefinitionMap.get(beanName);
09. if (oldBeanDefinition != null) {
10. if (!this.allowBeanDefinitionOverriding) {
11. ...........
12. }
13. else {
14. //把bean的名字加到IOC容器中去
15. this.beanDefinitionNames.add(beanName);
16. }
17. //这里把bean的名字和Bean定义联系起来放到一个HashMap中去,IOC容器通过这个Map来维护容器里的Bean定义信息。
18. this.beanDefinitionMap.put(beanName, beanDefinition);
19. removeSingleton(beanName);
20. }

```
    //---------------------------------------------------------------------
    // 这里是IOC容器对BeanDefinitionRegistry接口的实现
    //---------------------------------------------------------------------

    public void registerBeanDefinition(String beanName, BeanDefinition beanDefinition)
            throws BeanDefinitionStoreException {

        .....//这里省略了对BeanDefinition的验证过程
        //先看看在容器里是不是已经有了同名的bean,如果有抛出异常。
        Object oldBeanDefinition = this.beanDefinitionMap.get(beanName);
        if (oldBeanDefinition != null) {
            if (!this.allowBeanDefinitionOverriding) {
            ...........
        }
        else {
            //把bean的名字加到IOC容器中去
            this.beanDefinitionNames.add(beanName);
        }
        //这里把bean的名字和Bean定义联系起来放到一个HashMap中去,IOC容器通过这个Map来维护容器里的Bean定义信息。
        this.beanDefinitionMap.put(beanName, beanDefinition);
        removeSingleton(beanName);
    }
```

这样就完成了Bean定义在IOC容器中的注册，就可被IOC容器进行管理和使用了。  
从上面的代码来看，我们总结一下IOC容器初始化的基本步骤：

    * 初始化的入口在容器实现中的refresh()调用来完成  
    * 对bean 定义载入IOC容器使用的方法是loadBeanDefinition,其中的大致过程如下：通过ResourceLoader来完成资源文件位置的定位，DefaultResourceLoader是默认的实现，同时上下文本身就给出了ResourceLoader的实现，可以从类路径，文件系统, URL等方式来定为资源位置。如果是XmlBeanFactory作为IOC容器，那么需要为它指定bean定义的资源，也就是说bean定义文件时通过抽象成Resource来被IOC容器处理的，容器通过BeanDefinitionReader来完成定义信息的解析和Bean信息的注册,往往使用的是XmlBeanDefinitionReader来解析bean的xml定义文件 - 实际的处理过程是委托给BeanDefinitionParserDelegate来完成的，从而得到bean的定义信息，这些信息在Spring中使用BeanDefinition对象来表示 - 这个名字可以让我们想到loadBeanDefinition,RegisterBeanDefinition这些相关的方法 - 他们都是为处理BeanDefinitin服务的，IoC容器解析得到BeanDefinition以后，需要把它在IOC容器中注册，这由IOC实现 BeanDefinitionRegistry接口来实现。注册过程就是在IOC容器内部维护的一个HashMap来保存得到的 BeanDefinition的过程。这个HashMap是IoC容器持有bean信息的场所，以后对bean的操作都是围绕这个HashMap来实现的。  
    * 然后我们就可以通过BeanFactory和ApplicationContext来享受到Spring IOC的服务了.  
在使用IOC容器的时候，我们注意到除了少量粘合代码，绝大多数以正确IoC风格编写的应用程序代码完全不用关心如何到达工厂，因为容器将把这些对象与容器管理的其他对象钩在一起。基本的策略是把工厂放到已知的地方，最好是放在对预期使用的上下文有意义的地方，以及代码将实际需要访问工厂的地方。 Spring本身提供了对声明式载入web应用程序用法的应用程序上下文，并将其存储在ServletContext中的框架实现。具体可以参见以后的文章。  
在使用Spring IOC容器的时候我们还需要区别两个概念：  
Beanfactory 和Factory bean，其中BeanFactory指的是IOC容器的编程抽象，比如ApplicationContext， XmlBeanFactory等，这些都是IOC容器的具体表现，需要使用什么样的容器由客户决定但Spring为我们提供了丰富的选择。而 FactoryBean只是一个可以在IOC容器中被管理的一个bean,是对各种处理过程和资源使用的抽象,Factory bean在需要时产生另一个对象，而不返回FactoryBean本省，我们可以把它看成是一个抽象工厂，对它的调用返回的是工厂生产的产品。所有的 Factory bean都实现特殊的org.springframework.beans.factory.FactoryBean接口，当使用容器中factory bean的时候，该容器不会返回factory bean本身，而是返回其生成的对象。Spring包括了大部分的通用资源和服务访问抽象的Factory bean的实现，其中包括：  
对JNDI查询的处理，对代理对象的处理，对事务性代理的处理，对RMI代理的处理等，这些我们都可以看成是具体的工厂，看成是SPRING为我们建立好的工厂。也就是说Spring通过使用抽象工厂模式为我们准备了一系列工厂来生产一些特定的对象，免除我们手工重