【初探Spring】——Spring IOC(三):初始化过程—Resource定位

【初探Spring】——Spring IOC(三):初始化过程—Resource定位

原创  2016年06月27日 12:43:49

我们知道Spring的IoC起到了一个容器的作用,其中装得都是各种各样的Bean。同时在我们刚刚开始学习Spring的时候都是通过xml文件来定义Bean,Spring会某种方式加载这些xml文件,然后根据这些信息绑定整个系统的对象,最终组装成一个可用的基于轻量级容器的应用系统。

Spring IoC容器整体可以划分为两个阶段,容器启动阶段,Bean实例化阶段。其中容器启动阶段蛀牙包括加载配置信息、解析配置信息,装备到BeanDefinition中以及其他后置处理,而Bean实例化阶段主要包括实例化对象,装配依赖,生命周期管理已经注册回调。下面LZ先介绍容器的启动阶段的第一步,即定位配置文件。

我们使用编程方式使用DefaultListableBeanFactory时,首先是需要定义一个Resource来定位容器使用的BeanDefinition。

[java]  view plain  copy
  1. ClassPathResource resource = new ClassPathResource("bean.xml");  

通过这个代码,就意味着Spring会在类路径中去寻找bean.xml并解析为BeanDefinition信息。当然这个Resource并不能直接被使用,他需要被BeanDefinitionReader进行解析处理(这是后面的内容了)。

对于各种applicationContext,如FileSystemXmlApplicationContext、ClassPathXmlApplicationContext等等,我们从这些类名就可以看到他们提供了那些Resource的读入功能。下面我们以FileSystemXmlApplicationContext为例来阐述Spring IoC容器的Resource定位。

先看FileSystemXmlApplicationContext继承体系结构:


从图中可以看出FileSystemXMLApplicationContext继承了DefaultResourceLoader,具备了Resource定义的BeanDefinition的能力,其源代码如下:

[java]  view plain  copy
  1. public class FileSystemXmlApplicationContext extends AbstractXmlApplicationContext {  
  2.     /** 
  3.      * 默认构造函数 
  4.      */  
  5.     public FileSystemXmlApplicationContext() {  
  6.     }  
  7.   
  8.     public FileSystemXmlApplicationContext(ApplicationContext parent) {  
  9.         super(parent);  
  10.     }  
  11.   
  12.     public FileSystemXmlApplicationContext(String configLocation) throws BeansException {  
  13.         this(new String[] {configLocation}, truenull);  
  14.     }  
  15.   
  16.     public FileSystemXmlApplicationContext(String... configLocations) throws BeansException {  
  17.         this(configLocations, truenull);  
  18.     }  
  19.   
  20.     public FileSystemXmlApplicationContext(String[] configLocations, ApplicationContext parent) throws BeansException {  
  21.         this(configLocations, true, parent);  
  22.     }  
  23.   
  24.     public FileSystemXmlApplicationContext(String[] configLocations, boolean refresh) throws BeansException {  
  25.         this(configLocations, refresh, null);  
  26.     }  
  27.       
  28.     //核心构造器  
  29.     public FileSystemXmlApplicationContext(String[] configLocations, boolean refresh, ApplicationContext parent)  
  30.             throws BeansException {  
  31.   
  32.         super(parent);  
  33.         setConfigLocations(configLocations);  
  34.         if (refresh) {  
  35.             refresh();  
  36.         }  
  37.     }  
  38.   
  39.     //通过构造一个FileSystemResource对象来得到一个在文件系统中定位的BeanDefinition  
  40.     //采用模板方法设计模式,具体的实现用子类来完成  
  41.     protected Resource getResourceByPath(String path) {  
  42.         if (path != null && path.startsWith("/")) {  
  43.             path = path.substring(1);  
  44.         }  
  45.         return new FileSystemResource(path);  
  46.     }  
  47.   
  48. }  

AbstractApplicationContext中的refresh()方法是IoC容器初始化的入口,也就是说IoC容器的初始化是通过refresh()方法来完成整个调用过程的。在核心构造器中就对refresh进行调用,通过它来启动IoC容器的初始化工作。getResourceByPath为一个模板方法,通过构造一个FileSystemResource对象来得到一个在文件系统中定位的BeanDEfinition。getResourceByPath的调用关系如下(部分):


refresh为初始化IoC容器的入口,但是具体的资源定位还是在XmlBeanDefinitionReader读入BeanDefinition时完成,loadBeanDefinitions() 加载BeanDefinition的载入。

[java]  view plain  copy
  1. protected final void refreshBeanFactory() throws BeansException {  
  2.         //判断是否已经创建了BeanFactory,如果创建了则销毁关闭该BeanFactory  
  3.         if (hasBeanFactory()) {  
  4.             destroyBeans();  
  5.             closeBeanFactory();  
  6.         }  
  7.         try {  
  8.             //创建DefaultListableBeanFactory实例对象  
  9.             DefaultListableBeanFactory beanFactory = createBeanFactory();  
  10.             beanFactory.setSerializationId(getId());  
  11.             customizeBeanFactory(beanFactory);  
  12.             //加载BeanDefinition信息  
  13.             loadBeanDefinitions(beanFactory);  
  14.             synchronized (this.beanFactoryMonitor) {  
  15.                 this.beanFactory = beanFactory;  
  16.             }  
  17.         }  
  18.         catch (IOException ex) {  
  19.             throw new ApplicationContextException("I/O error parsing bean definition source for " + getDisplayName(), ex);  
  20.         }  
  21.     }  

DefaultListableBeanFactory作为BeanFactory默认实现类,其重要性不言而喻,而createBeanFactory()则返回该实例对象。

[java]  view plain  copy
  1. protected DefaultListableBeanFactory createBeanFactory() {  
  2.         return new DefaultListableBeanFactory(getInternalParentBeanFactory());  
  3.     }  

loadBeanDefinition方法加载BeanDefinition信息,BeanDefinition就是在这里定义的。AbstractRefreshableApplicationContext对loadBeanDefinitions仅仅只是定义了一个抽象的方法,真正的实现类为其子类AbstractXmlApplicationContext来实现:

AbstractRefreshableApplicationContext:

[java]  view plain  copy
  1. protected abstract void loadBeanDefinitions(DefaultListableBeanFactory beanFactory)  
  2.             throws BeansException, IOException;  

AbstractXmlApplicationContext:

[java]  view plain  copy
  1. protected void loadBeanDefinitions(DefaultListableBeanFactory beanFactory) throws BeansException, IOException {  
  2.         //创建bean的读取器(Reader),即XmlBeanDefinitionReader,并通过回调设置到容器中  
  3.         XmlBeanDefinitionReader beanDefinitionReader = new XmlBeanDefinitionReader(beanFactory);  
  4.   
  5.         //  
  6.         beanDefinitionReader.setEnvironment(getEnvironment());  
  7.         //为Bean读取器设置Spring资源加载器  
  8.         beanDefinitionReader.setResourceLoader(this);  
  9.         //为Bean读取器设置SAX xml解析器  
  10.         beanDefinitionReader.setEntityResolver(new ResourceEntityResolver(this));  
  11.   
  12.         //  
  13.         initBeanDefinitionReader(beanDefinitionReader);  
  14.         //Bean读取器真正实现的地方  
  15.         loadBeanDefinitions(beanDefinitionReader);  
  16.     }  

程序首先首先创建一个Reader,在前面就提到过,每一类资源都对应着一个BeanDefinitionReader,BeanDefinitionReader提供统一的转换规则;然后设置Reader,最后调用loadBeanDefinition,该loadBeanDefinition才是读取器真正实现的地方:

[java]  view plain  copy
  1. protected void loadBeanDefinitions(XmlBeanDefinitionReader reader) throws BeansException, IOException {  
  2.         //获取Bean定义资源的定位  
  3.         Resource[] configResources = getConfigResources();  
  4.         if (configResources != null) {  
  5.             reader.loadBeanDefinitions(configResources);  
  6.         }  
  7.         //获取Bean定义资源的路径。在FileSystemXMLApplicationContext中通过setConfigLocations可以配置Bean资源定位的路径  
  8.         String[] configLocations = getConfigLocations();  
  9.         if (configLocations != null) {  
  10.             reader.loadBeanDefinitions(configLocations);  
  11.         }  
  12.     }  

首先通过getConfigResources()获取Bean定义的资源定位,如果不为null则调用loadBeanDefinitions方法来读取Bean定义资源的定位。

loadBeanDefinitions是中的方法:

[java]  view plain  copy
  1. public int loadBeanDefinitions(String... locations) throws BeanDefinitionStoreException {  
  2.         Assert.notNull(locations, "Location array must not be null");  
  3.         int counter = 0;  
  4.         for (String location : locations) {  
  5.             counter += loadBeanDefinitions(location);  
  6.         }  
  7.         return counter;  
  8.     }  

继续:

[java]  view plain  copy
  1. public int loadBeanDefinitions(String location) throws BeanDefinitionStoreException {  
  2.         return loadBeanDefinitions(location, null);  
  3.     }  

再继续:

[java]  view plain  copy
  1. public int loadBeanDefinitions(String location, Set<Resource> actualResources) throws BeanDefinitionStoreException {  
  2.         //获取ResourceLoader资源加载器  
  3.         ResourceLoader resourceLoader = getResourceLoader();  
  4.         if (resourceLoader == null) {  
  5.             throw new BeanDefinitionStoreException(  
  6.                     "Cannot import bean definitions from location [" + location + "]: no ResourceLoader available");  
  7.         }  
  8.   
  9.         //  
  10.         if (resourceLoader instanceof ResourcePatternResolver) {  
  11.             try {  
  12.                 //调用DefaultResourceLoader的getResourceByPath完成具体的Resource定位  
  13.                 Resource[] resources = ((ResourcePatternResolver) resourceLoader).getResources(location);  
  14.                 int loadCount = loadBeanDefinitions(resources);  
  15.                 if (actualResources != null) {  
  16.                     for (Resource resource : resources) {  
  17.                         actualResources.add(resource);  
  18.                     }  
  19.                 }  
  20.                 if (logger.isDebugEnabled()) {  
  21.                     logger.debug("Loaded " + loadCount + " bean definitions from location pattern [" + location + "]");  
  22.                 }  
  23.                 return loadCount;  
  24.             }  
  25.             catch (IOException ex) {  
  26.                 throw new BeanDefinitionStoreException(  
  27.                         "Could not resolve bean definition resource pattern [" + location + "]", ex);  
  28.             }  
  29.         }  
  30.         else {  
  31.             //调用DefaultResourceLoader的getResourceByPath完成具体的Resource定位  
  32.             Resource resource = resourceLoader.getResource(location);  
  33.             int loadCount = loadBeanDefinitions(resource);  
  34.             if (actualResources != null) {  
  35.                 actualResources.add(resource);  
  36.             }  
  37.             if (logger.isDebugEnabled()) {  
  38.                 logger.debug("Loaded " + loadCount + " bean definitions from location [" + location + "]");  
  39.             }  
  40.             return loadCount;  
  41.         }  
  42.     }  

在这段源代码中通过调用DefaultResourceLoader的getResource方法:

[java]  view plain  copy
  1. public Resource getResource(String location) {  
  2.         Assert.notNull(location, "Location must not be null");  
  3.         if (location.startsWith("/")) {  
  4.             return getResourceByPath(location);  
  5.         }  
  6.         //处理带有classPath标识的Resource  
  7.         else if (location.startsWith(CLASSPATH_URL_PREFIX)) {  
  8.             return new ClassPathResource(location.substring(CLASSPATH_URL_PREFIX.length()), getClassLoader());  
  9.         }  
  10.         else {  
  11.             try {  
  12.                 //处理URL资源  
  13.                 URL url = new URL(location);  
  14.                 return new UrlResource(url);  
  15.             }  
  16.             catch (MalformedURLException ex) {  
  17.                 return getResourceByPath(location);  
  18.             }  
  19.         }  
  20.     }  

在getResource方法中我们可以清晰地看到Resource资源的定位。这里可以清晰地看到getResourceByPath方法的调用,getResourceByPath方法的具体实现有子类来完成,在FileSystemXmlApplicationContext实现如下:

[java]  view plain  copy
  1. protected Resource getResourceByPath(String path) {  
  2.         if (path != null && path.startsWith("/")) {  
  3.             path = path.substring(1);  
  4.         }  
  5.         return new FileSystemResource(path);  
  6.     }  

这样代码就回到了博客开初的FileSystemXmlApplicationContext 中来了,它提供了FileSystemResource 来完成从文件系统得到配置文件的资源定义。当然这仅仅只是Spring IoC容器定位资源的一种逻辑,我们可以根据这个步骤来查看Spring提供的各种资源的定位,如ClassPathResource、URLResource等等。下图是ResourceLoader的继承关系:

这里就差不多分析了Spring IoC容器初始化过程资源的定位,在BeanDefinition定位完成的基础上,就可以通过返回的Resource对象来进行BeanDefinition的载入、解析了。

下篇博客将探索Spring IoC容器初始化过程的解析,Spring Resource体系结构会在后面详细讲解。

 

参考文献

1、《Spring技术内幕 深入解析Spring架构与设计原理》–第二版

2、Spring:源码解读Spring IOC原理

3、【Spring】IOC核心源码学习(二):容器初始化过程

版权声明:版权声明:转载前请留言获得作者许可,转载后标明作者 chenssy 和原文出处。原创不易,感谢您的支持
 
xcxc_java
  • xcxc_java
    2017-10-10 18:385楼
  • 引用“chenssy”的评论:回复zhugeyangyang1994:一起学习
u010668026
wocena
  • wocena
    2016-09-10 15:463楼
  • 很喜欢博主的文章,刚刚用豆约翰博客备份专家备份了您的全部博文。
wocena
  • wocena
    2016-09-10 15:422楼
  • 很喜欢博主的文章,刚刚用豆约翰博客备份专家备份了您的全部博文。
zhugeyangyang1994
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值