`
huibin
  • 浏览: 739967 次
  • 性别: Icon_minigender_1
  • 来自: 郑州
社区版块
存档分类
最新评论

Spring源代码解析(一):IOC容器

阅读更多

在Spring中,IOC容器的重要地位我们就不多说了,对于Spring的使用者而言,IOC容器实际上是什么呢?我们可以说 BeanFactory就是我们看到的IoC容器,当然了Spring为我们准备了许多种IoC容器来使用,这样可以方便我们从不同的层面,不同的资源位 置,不同的形式的定义信息来建立我们需要的IoC容器。
在Spring中,最基本的IOC容器接口是BeanFactory - 这个接口为具体的IOC容器的实现作了最基本的功能规定 - 不管怎么着,作为IOC容器,这些接口你必须要满足应用程序的最基本要求:

Java代码 复制代码
  1. public   interface  BeanFactory {   
  2.   
  3.      //这里是对FactoryBean的转义定义,因为如果使用 bean的名字检索FactoryBean得到的对象是工厂生成的对象,   
  4.      //如果需要得到工厂本身,需要转义          
  5.     String FACTORY_BEAN_PREFIX =  "&" ;   
  6.   
  7.   
  8.      //这里根据bean的名字,在IOC容器中得到bean实 例,这个IOC容器就是一个大的抽象工厂。   
  9.     Object getBean(String name)  throws  BeansException;   
  10.   
  11.      //这里根据bean的名字和Class类型来得到bean实 例,和上面的方法不同在于它会抛出异常:如果根据名字取得的bean实例的Class类型和需要的不同的话。   
  12.     Object getBean(String name, Class requiredType)  throws  BeansException;   
  13.   
  14.      //这里提供对bean的检索,看看是否在IOC容器有这个名 字的bean   
  15.      boolean  containsBean(String name);   
  16.   
  17.      //这里根据bean名字得到bean实例,并同时判断这个 bean是不是单件   
  18.      boolean  isSingleton(String name)  throws  NoSuchBeanDefinitionException;   
  19.   
  20.      //这里对得到bean实例的Class类型   
  21.     Class getType(String name)  throws  NoSuchBeanDefinitionException;   
  22.   
  23.      //这里得到bean的别名,如果根据别名检索,那么其原名也 会被检索出来   
  24.     String[] getAliases(String name);   
  25.   
  26. }  
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代码 复制代码
  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代码 复制代码
  1. public   class  XmlBeanFactory  extends  DefaultListableBeanFactory {   
  2.      //这里为容器定义了一个默认使用的bean定义读取器   
  3.      private   final  XmlBeanDefinitionReader reader =  new  XmlBeanDefinitionReader( this );   
  4.      public  XmlBeanFactory(Resource resource)  throws  BeansException {   
  5.          this (resource,  null );   
  6.     }   
  7.      //在初始化函数中使用读取器来对资源进行读取,得到bean 定义信息。   
  8.      public  XmlBeanFactory(Resource resource, BeanFactory parentBeanFactory)  throws  BeansException {   
  9.          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代码 复制代码
  1. ApplicationContext =  new  FileSystemXmlApplicationContext(xmlPath);  
   ApplicationContext = new FileSystemXmlApplicationContext(xmlPath);


调用的是它初始化代码:

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

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


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

Java代码 复制代码
  1. protected   void  loadBeanDefinitions(DefaultListableBeanFactory beanFactory)  throws  IOException {   
  2.      // 这里使用 XMLBeanDefinitionReader来载入bean定义信息的XML文件   
  3.     XmlBeanDefinitionReader beanDefinitionReader =  new  XmlBeanDefinitionReader(beanFactory);   
  4.   
  5.      //这里配置reader的环境,其中 ResourceLoader是我们用来定位bean定义信息资源位置的   
  6.      ///因为上下文本身实现了ResourceLoader接 口,所以可以直接把上下文作为ResourceLoader传递给XmlBeanDefinitionReader   
  7.     beanDefinitionReader.setResourceLoader( this );   
  8.     beanDefinitionReader.setEntityResolver( new  ResourceEntityResolver( this ));   
  9.   
  10.     initBeanDefinitionReader(beanDefinitionReader);   
  11.      //这里转到定义好的 XmlBeanDefinitionReader中对载入bean信息进行处理   
  12.     loadBeanDefinitions(beanDefinitionReader);   
  13. }  
    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代码 复制代码
  1. protected   void  loadBeanDefinitions(XmlBeanDefinitionReader reader)  throws  BeansException, IOException {   
  2.     Resource[] configResources = getConfigResources();   
  3.      if  (configResources !=  null ) {   
  4.          //调用 XmlBeanDefinitionReader来载入bean定义信息。   
  5.         reader.loadBeanDefinitions(configResources);   
  6.     }   
  7.     String[] configLocations = getConfigLocations();   
  8.      if  (configLocations !=  null ) {   
  9.         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代码 复制代码
  1. public   int  loadBeanDefinitions(String location)  throws  BeanDefinitionStoreException {   
  2.   //这里得到当前定义的ResourceLoader,默认的我们使 用DefaultResourceLoader   
  3.  ResourceLoader resourceLoader = getResourceLoader();   
  4.  ......... //如果没有找到我们需要的 ResourceLoader,直接抛出异常   
  5.      if  (resourceLoader  instanceof  ResourcePatternResolver) {   
  6.          // 这里处理我们在定义位置时使用的各种 pattern,需要ResourcePatternResolver来完成   
  7.          try  {   
  8.             Resource[] resources = ((ResourcePatternResolver) resourceLoader).getResources(location);   
  9.              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代码 复制代码
  1. public   class  GenericApplicationContext  extends  AbstractApplicationContext  implements  BeanDefinitionRegistry {   
  2.      public  Resource getResource(String location) {   
  3.          //这里调用当前的loader也就是 DefaultResourceLoader来完成载入   
  4.          if  ( this .resourceLoader !=  null ) {   
  5.              return   this .resourceLoader.getResource(location);   
  6.         }   
  7.          return   super .getResource(location);   
  8.     }   
  9. .......   
  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代码 复制代码
  1. public  Resource getResource(String location) {   
  2.      //如果是类路径的方式,那需要使用 ClassPathResource来得到bean文件的资源对象   
  3.      if  (location.startsWith(CLASSPATH_URL_PREFIX)) {   
  4.          return   new  ClassPathResource(location.substring(CLASSPATH_URL_PREFIX.length()), getClassLoader());   
  5.     }   
  6.      else  {   
  7.          try  {   
  8.              // 如果是URL方式,使用 UrlResource作为bean文件的资源对象   
  9.             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代码 复制代码
  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代码 复制代码
  1. public   int  loadBeanDefinitions(EncodedResource encodedResource)  throws  BeanDefinitionStoreException {   
  2.     .......   
  3.      try  {   
  4.          //这里通过Resource得到 InputStream的IO流   
  5.         InputStream inputStream = encodedResource.getResource().getInputStream();   
  6.          try  {   
  7.              //从InputStream中得到XML的 解析源   
  8.             InputSource inputSource =  new  InputSource(inputStream);   
  9.              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.   
  23. protected   int  doLoadBeanDefinitions(InputSource inputSource, Resource resource)   
  24.          throws  BeanDefinitionStoreException {   
  25.      try  {   
  26.          int  validationMode = getValidationModeForResource(resource);   
  27.          //通过解析得到DOM,然后完成bean在IOC容 器中的注册   
  28.         Document doc =  this .documentLoader.loadDocument(   
  29.                 inputSource,  this .entityResolver,  this .errorHandler, validationMode,  this .namespaceAware);   
  30.          return  registerBeanDefinitions(doc, resource);   
  31.     }   
  32. .......   
  33. }  
    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代码 复制代码
  1. public   int  registerBeanDefinitions(Document doc, Resource resource)  throws  BeanDefinitionStoreException {   
  2.      // 这里定义解析器,使用 XmlBeanDefinitionParser来解析xml方式的bean定义文件 - 现在的版本不用这个解析器了,使用的是 XmlBeanDefinitionReader   
  3.      if  ( this .parserClass !=  null ) {   
  4.         XmlBeanDefinitionParser parser =   
  5.                 (XmlBeanDefinitionParser) BeanUtils.instantiateClass( this .parserClass);   
  6.          return  parser.registerBeanDefinitions( this , doc, resource);   
  7.     }   
  8.      // 具体的注册过程,首先得到 XmlBeanDefinitionReader,来处理xml的bean定义文件   
  9.     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代码 复制代码
  1. public   void  registerBeanDefinitions(Document doc, XmlReaderContext readerContext) {   
  2.      this .readerContext = readerContext;   
  3.   
  4.     logger.debug( "Loading bean definitions" );   
  5.     Element root = doc.getDocumentElement();   
  6.   
  7.     BeanDefinitionParserDelegate delegate = createHelper(readerContext, root);   
  8.   
  9.     preProcessXml(root);   
  10.     parseBeanDefinitions(root, delegate);   
  11.     postProcessXml(root);   
  12. }   
  13.   
  14. protected   void  parseBeanDefinitions(Element root, BeanDefinitionParserDelegate delegate) {   
  15.      if  (delegate.isDefaultNamespace(root.getNamespaceURI())) {   
  16.          //这里得到xml文件的子节点,比如各个bean节 点            
  17.         NodeList nl = root.getChildNodes();   
  18.   
  19.          //这里对每个节点进行分析处理   
  20.          for  ( int  i =  0 ; i < nl.getLength(); i++) {   
  21.             Node node = nl.item(i);   
  22.              if  (node  instanceof  Element) {   
  23.                 Element ele = (Element) node;   
  24.                 String namespaceUri = ele.getNamespaceURI();   
  25.                  if  (delegate.isDefaultNamespace(namespaceUri)) {   
  26.                      //这里是解析过程的调用, 对缺省的元素进行分析比如bean元素   
  27.                     parseDefaultElement(ele, delegate);   
  28.                 }   
  29.                  else  {   
  30.                     delegate.parseCustomElement(ele);   
  31.                 }   
  32.             }   
  33.         }   
  34.     }  else  {   
  35.         delegate.parseCustomElement(root);   
  36.     }   
  37. }   
  38.   
  39. private   void  parseDefaultElement(Element ele, BeanDefinitionParserDelegate delegate) {   
  40.      //这里对元素Import进行处理   
  41.      if  (DomUtils.nodeNameEquals(ele, IMPORT_ELEMENT)) {   
  42.         importBeanDefinitionResource(ele);   
  43.     }   
  44.      else   if  (DomUtils.nodeNameEquals(ele, ALIAS_ELEMENT)) {   
  45.         String name = ele.getAttribute(NAME_ATTRIBUTE);   
  46.         String alias = ele.getAttribute(ALIAS_ATTRIBUTE);   
  47.         getReaderContext().getReader().getBeanFactory().registerAlias(name, alias);   
  48.         getReaderContext().fireAliasRegistered(name, alias, extractSource(ele));   
  49.     }   
  50.      //这里对我们最熟悉的bean元素进行处理   
  51.      else   if  (DomUtils.nodeNameEquals(ele, BEAN_ELEMENT)) {   
  52.          //委托给 BeanDefinitionParserDelegate来完成对bean元素的处理,这个类包含了具体的bean解析的过程。   
  53.          // 把解析bean文件得到的信息放到 BeanDefinition里,他是bean信息的主要载体,也是IOC容器的管理对象。   
  54.         BeanDefinitionHolder bdHolder = delegate.parseBeanDefinitionElement(ele);   
  55.          if  (bdHolder !=  null ) {   
  56.             bdHolder = delegate.decorateBeanDefinitionIfRequired(ele, bdHolder);   
  57.              // 这里是向IOC容器注册,实际上是放到 IOC容器的一个map里   
  58.             BeanDefinitionReaderUtils.registerBeanDefinition(bdHolder, getReaderContext().getRegistry());   
  59.   
  60.              // 这里向IOC容器发送事件,表示解析和 注册完成。   
  61.             getReaderContext().fireComponentRegistered( new  BeanComponentDefinition(bdHolder));   
  62.         }   
  63.     }   
  64. }  
    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代码 复制代码
  1. public   static   void  registerBeanDefinition(   
  2.         BeanDefinitionHolder bdHolder, BeanDefinitionRegistry beanFactory)  throws  BeansException {   
  3.   
  4.      // 这里得到需要注册bean的名字;   
  5.     String beanName = bdHolder.getBeanName();   
  6.      //这是调用IOC来注册的bean的过程,需要得到 BeanDefinition   
  7.     beanFactory.registerBeanDefinition(beanName, bdHolder.getBeanDefinition());   
  8.   
  9.      // 别名也是可以通过IOC容器和bean联系起来的进行注 册   
  10.     String[] aliases = bdHolder.getAliases();   
  11.      if  (aliases !=  null ) {   
  12.          for  ( int  i =  0 ; i < aliases.length; i++) {   
  13.             beanFactory.registerAlias(beanName, aliases[i]);   
  14.         }   
  15.     }   
  16. }  
    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代码 复制代码
  1. //---------------------------------------------------------------------   
  2. // 这里是IOC容器对BeanDefinitionRegistry接口的实现   
  3. //---------------------------------------------------------------------   
  4.   
  5. public   void  registerBeanDefinition(String beanName, BeanDefinition beanDefinition)   
  6.          throws  BeanDefinitionStoreException {   
  7.   
  8.     ..... //这里省略了对BeanDefinition的验 证过程   
  9.      //先看看在容器里是不是已经有了同名的bean,如果有抛出 异常。   
  10.     Object oldBeanDefinition =  this .beanDefinitionMap.get(beanName);   
  11.      if  (oldBeanDefinition !=  null ) {   
  12.          if  (! this .allowBeanDefinitionOverriding) {   
  13.         ...........   
  14.     }   
  15.      else  {   
  16.          //把bean的名字加到IOC容器中去   
  17.          this .beanDefinitionNames.add(beanName);   
  18.     }   
  19.      //这里把bean的名字和Bean定义联系起来放到一个 HashMap中去,IOC容器通过这个Map来维护容器里的Bean定义信息。   
  20.      this .beanDefinitionMap.put(beanName, beanDefinition);   
  21.     removeSingleton(beanName);   
  22. }  
    //---------------------------------------------------------------------
    // 这里是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定义文件 - 实际

分享到:
评论
4 楼 annybz 2013-08-28  
3 楼 waainli 2012-03-27  
写的挺好的。可是每段都有重复。显得有点乱。
2 楼 zhangtom468 2011-12-16  
不错,挺全面的
1 楼 flyzonemu 2011-07-17  
这么好的东西居然没人顶,支持一下!!!!

相关推荐

    Spring源代码解析(一):IOC容器.doc

    Spring源代码解析(一):IOC容器.doc

    Spring源代码解析

    Spring源代码解析(一):IOC容器 Spring源代码解析(二):IoC容器在Web容器中的启动 Spring源代码解析(三):Spring JDBC Spring源代码解析(四):Spring MVC Spring源代码解析(五):Spring AOP获取Proxy Spring源...

    Spring源代码解析.rar

    Spring源代码解析1:IOC容器.doc Spring源代码解析2:IoC容器在Web容器中的启动.doc Spring源代码解析3:Spring JDBC .doc Spring源代码解析4:Spring MVC .doc Spring源代码解析5:Spring AOP获取Proxy .doc Spring...

    Spring 源代码解析

    Spring源代码解析1:IOC容器;Spring源代码解析2:IoC容器在Web容器中的启动;Spring源代码解析3:Spring JDBC ; Spring源代码解析4:Spring MVC ;Spring源代码解析5:Spring AOP获取Proxy;Spring源代码解析6:...

    Spring源代码解析(二):IoC容器在Web容器中的启动.doc

    Spring源代码解析(二):IoC容器在Web容器中的启动.doc

    springyuanmaaping.zip

    Spring源代码解析2:IoC容器在Web容器中的启动;Spring源代码解析3:Spring JDBC ; Spring源代码解析4:Spring MVC ;Spring源代码解析5:Spring AOP获取Proxy;Spring源代码解析6:Spring声明式事务处理 ; ...

    spring源码分析(1-10)

    Spring源代码解析(二):ioc容器在Web容器中的启动 Spring源代码分析(三):Spring JDBC Spring源代码解析(四):Spring MVC Spring源代码解析(五):Spring AOP获取Proxy Spring源代码解析(六):Spring声明式事务处理...

    spring源码分析

    Spring源代码解析(二):ioc容器在Web容器中的启动 3.Spring源代码解析(三):Spring JDBC 4.Spring源代码解析(四):Spring MVC 5.Spring源代码解析(五):Spring AOP获取Proxy 6. Spring源代码解析(六):Spring...

    Spring源码学习文档,绝对值得好好研究~~

    Spring源代码解析(二):ioc容器在Web容器中的启动.doc Spring源代码分析(三):Spring JDBC.doc Spring源代码解析(四):Spring MVC.doc Spring源代码解析(五):Spring AOP获取Proxy.doc Spring源代码解析(六):...

    spring源代码解析

    简单的说,在web容器中,通过ServletContext为Spring的IOC容器提供宿主环境,对应的建立起一个IOC容器的体系。其中,首先需要建立的是根上下文,这个上下文持有的对象可以有业务对象,数据存取对象,资源,事物管理...

    Spring技术内幕:深入解析Spring架构与设计原理

    《Spring技术内幕:深入解析Spring架构与设计原理(第2版)》从源代码的角度对Spring的内核和各个主要功能模块的架构、设计和实现原理进行了深入剖析。你不仅能从本书中参透Spring框架的出色架构和设计思想,还能从...

    Spring技术内幕:深入解析 Spring架构与设计原理.pdf

    第一部分详细分析了Spring的核心:IoC容器和AOP的实现,能帮助读者了解Spring的运行机制;第二部分深入阐述了各种基于IoC容器和AOP的Java EE组件在Spring中的实现原理;第三部分讲述了ACEGI安全框架、DM模块以及Flex...

    Spring技术内幕:深入解析Spring架构与设计原理(第2部分)

     揭开Spring源代码的神秘面纱,展示系统阅读开源软件源代码的方法和秘诀。  如果你正在思考下面这些问题,也许《Spring技术内幕:深入解析Spring架构与设计原理》就是你想要的!  掌握Spring的架构原理与设计思想...

    Spring技术内幕:深入解析Spring架构与设计原理(第2版)

    第一部分详细分析了spring的核心:ioc容器和aop的实现,能帮助读者了解spring的运行机制;第二部分深入阐述了各种基于ioc容器和aop的java ee组件在spring中的实现原理;第三部分讲述了acegi安全框架、dm模块以及flex...

    Spring技术内幕:深入解析Spring架构与设计原理(第2版) 决战大数据时代!IT技术人员不得不读! 计文柯 著

    《Spring技术内幕:深入解析Spring架构与设计原理(第2版)》是国内一本系统分析Spring源代码的著作,也是Spring领域的问鼎之作,由业界拥有10余年开发经验的专业Java专家亲自执笔,Java开发者社区和Spring开发者...

    Spring技术内幕:深入解析Spring架构与设计原理(第2版)

    Spring技术内幕:深入解析Spring架构与设计原理(第2版)》是国内唯一一本系统分析Spring源代码的著作,也是Spring领域的问鼎之作,由业界拥有10余年开发经验的资深Java专家亲自执笔,Java开发者社区和Spring开发者...

Global site tag (gtag.js) - Google Analytics