现在的位置: 首页 > 综合 > 正文

转:Spring源码分析:IOC容器

2012年01月16日 ⁄ 综合 ⁄ 共 11813字 ⁄ 字号 评论关闭
在认真学习Rod.Johnson的三部曲之一:<<Professional Java Development with the spring framework>>,顺便也看了看源代码想知道个究竟,抛砖引玉,有兴趣的同志一起讨论研究吧! 
以下内容引自博客:http://jiwenke-spring.blogspot.com/,欢迎指导:) 
在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. }  

在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);  

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

   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.     }  

我们在后面会看到读取器读取资源和注册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);  

调用的是它初始化代码: 

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. }  

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.  }  

这个方法包含了整个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. }  

转到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. }  

而在作为其抽象父类的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. }  

当我们通过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. }  

而我们的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. }  

我们的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. }  

这样代码就回到了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. }  

我们看到先把定义文件解析为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. }  

具体的在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();  

抱歉!评论已关闭.