Spring源码--IOC容器实现(2)--BeanDefinition的Resource定位

前言

Github:https://github.com/yihonglei/thinking-in-spring

一 IOC容器初始化过程概述

    IOC容器初始化是由上文提到的refresh()方法来启动的,这个方法标志着IOC容器正式启动。

IOC容器初始化过程分为三个过程:

1)BeanDefinition的Resource定位过程。

    这个Resource定位是指BeanDefinition资源定位,它由ResourceLoader通过统一的Resource

接口完成。这个定位过程就是容器寻找数据的过程,就像水桶要装水首先需要找到水一样。

2)BeanDefinition的载入和解析过程。

    这个过程就是根据上一步定位的Resource资源文件,把用户定义好的Bean表示成IOC容器内部的

BeanDefinition数据结构。BeanDefinition实际就是POJO对象在IOC容器中的抽象,通过BeanDefinition

定义数据结构,使IOC容器能够方便地对POJO对象也就是Bean进行管理。

3)向IOC容器注册BeanDefinition的过程。

    这个过程是通过调用BeanDefinitionRegistry接口的实现来完成的,把载入过程生成的BeanDefinition向

IOC容器注册。最终在IOC容器内部将BeanDefinition注入到一个HashMap中,IOC容器就是通过这个

HashMap来持有这些BeanDefinition数据的。

注意:

    这里需要注意的是,上面谈到的只是IOC容器的初始化过程,这个过程一般不包含Bean依赖注入的实现。

Bean的定义和依赖注入是两个独立的过程。依赖注入一般发生在第一次getBean()向容器索要Bean的时候,

但是如果配置了lazyinit,则初始化的时候这样的Bean已经触发了依赖注入。

这里先分析IOC容器的第一个过程,BeanDefinition的Resource定位过程。

二 BeanDefinition的Resource定位过程

    一般我们通常使用的IOC容器有FileSystemXmlApplicationContext、ClassPathXmlApplicationContext、

XmlWebApplicationContext、WebApplicationContext等。下面以FileSystemXmlApplicationContext为例,

分析Resource的定位过程。

FileSystemXmlApplicationContext应用:


 
 
  1. // 根据配置文件创建IOC容器
  2. ApplicationContext context =
  3. new FileSystemXmlApplicationContext( "classpath:applicationContext.xml");
  4. // 从容器中获取Bean
  5. ConferenceServiceImpl conferenceService = (ConferenceServiceImpl)context.getBean( "conferenceService");
  6. // 调用Bean方法
  7. conferenceService.conference();

FileSystemXmlApplicationContext类图:

"实线"代表extends,"虚线"代表implements。从类图可以看到继承了ApplicationContext,而ApplicationContext

又继承了BeanFactory,所以FileSystemXmlApplicationContext具备了IOC的基本规范和一些高级特性。

在类图的最右上方可以看到继承了ResourceLoader,用以读入以Resource定义的BeanDefinition的能力。

FileSystemXmlApplicationContext源码:


 
 
  1. package org.springframework.context.support;
  2. import org.springframework.beans.BeansException;
  3. import org.springframework.context.ApplicationContext;
  4. import org.springframework.core.io.FileSystemResource;
  5. import org.springframework.core.io.Resource;
  6. public class FileSystemXmlApplicationContext extends AbstractXmlApplicationContext {
  7. public FileSystemXmlApplicationContext() {
  8. }
  9. public FileSystemXmlApplicationContext(ApplicationContext parent) {
  10. super(parent);
  11. }
  12. /**
  13. * 根据用户定义的Bean XML文件路径,载入BeanDefinition,自动创建IOC容器
  14. */
  15. public FileSystemXmlApplicationContext(String configLocation) throws BeansException {
  16. this( new String[] {configLocation}, true, null);
  17. }
  18. /**
  19. * 根据用户定义的多个Bean XML文件路径,载入BeanDefinition,自动创建IOC容器
  20. */
  21. public FileSystemXmlApplicationContext(String... configLocations) throws BeansException {
  22. this(configLocations, true, null);
  23. }
  24. /**
  25. * 根据用户定义的多个Bean XML文件路径,载入BeanDefinition,自动创建IOC容器,允许指定自己的双亲IOC容器
  26. */
  27. public FileSystemXmlApplicationContext(String[] configLocations, ApplicationContext parent) throws BeansException {
  28. this(configLocations, true, parent);
  29. }
  30. /**
  31. * 是否允许自动刷新上下文
  32. */
  33. public FileSystemXmlApplicationContext(String[] configLocations, boolean refresh) throws BeansException {
  34. this(configLocations, refresh, null);
  35. }
  36. /**
  37. * 在对象初始化的过程中,调用refresh()方法启动载入BeanDefinition过程
  38. */
  39. public FileSystemXmlApplicationContext(String[] configLocations, boolean refresh, ApplicationContext parent)
  40. throws BeansException {
  41. super(parent);
  42. setConfigLocations(configLocations);
  43. if (refresh) {
  44. refresh();
  45. }
  46. }
  47. /**
  48. * 根据用户的xml构建Resource对象,这是一个模板方法,
  49. * 在BeanDefinitionReader的loadBeanDefinition()方法中被调用。
  50. */
  51. @Override
  52. protected Resource getResourceByPath(String path) {
  53. if (path != null && path.startsWith( "/")) {
  54. path = path.substring( 1);
  55. }
  56. return new FileSystemResource(path);
  57. }
  58. }

    FileSystemXmlApplicationContext中有很多构造函数,实现了对参数configLocation进行处理,以XML文件方式

存在的BeanDefinition能够得到有效处理。比如,实现了getResourceByPath()方法,这个是一个模板方法,是为

读取Resource服务的。在初始化FileSystemXmlApplicationContext的过程中,通过refresh()来启动整个调用,

进入AbstractApplicationContext的refresh()方法。

AbstractApplicationContext.refresh()方法源码:


 
 
  1. @Override
  2. public void refresh() throws BeansException, IllegalStateException {
  3. synchronized ( this.startupShutdownMonitor) {
  4. // Prepare this context for refreshing.
  5. // 调用容器准备刷新的方法,设置容器的启动时间为当前时间,容器关闭状态为false,同时给容器设置同步标识
  6. prepareRefresh();
  7. // Tell the subclass to refresh the internal bean factory.
  8. // 告诉子类启动refreshBeanFactory()方法,
  9. // Bean定义资源文件的载入从子类的refreshBeanFactory()方法启动[***重点***]
  10. ConfigurableListableBeanFactory beanFactory = obtainFreshBeanFactory();
  11. // Prepare the bean factory for use in this context.
  12. // 为BeanFactory配置容器特性,例如类加载器、事件处理器等
  13. prepareBeanFactory(beanFactory);
  14. try {
  15. // Allows post-processing of the bean factory in context subclasses.
  16. // 为容器的某些子类指定特殊的BeanPost事件处理器,进行后置处理
  17. postProcessBeanFactory(beanFactory);
  18. // Invoke factory processors registered as beans in the context.
  19. // 调用BeanFactory的后置处理器,这些后置处理器是在Bean定义中向容器注册的
  20. invokeBeanFactoryPostProcessors(beanFactory);
  21. // Register bean processors that intercept bean creation.
  22. // 为BeanFactory注册BeanPost事件处理器,BeanPostProcessor是Bean后置处理器,用于监听容器触发的事件
  23. registerBeanPostProcessors(beanFactory);
  24. // Initialize message source for this context.
  25. // 初始化信息源,和国际化相关
  26. initMessageSource();
  27. // Initialize event multicaster for this context.
  28. // 初始化容器事件传播器
  29. initApplicationEventMulticaster();
  30. // Initialize other special beans in specific context subclasses.
  31. // 调用子类的某些特殊Bean初始化方法
  32. onRefresh();
  33. // Check for listener beans and register them.
  34. // 检查监听Bean并且将这些Bean向容器注册
  35. registerListeners();
  36. // Instantiate all remaining (non-lazy-init) singletons.
  37. // 初始化所有剩余的(non-lazy-init)单态Bean
  38. finishBeanFactoryInitialization(beanFactory);
  39. // Last step: publish corresponding event.
  40. // 初始化容器的生命周期事件处理器,并发布容器的生命周期事件,结束refresh过程
  41. finishRefresh();
  42. }
  43. catch (BeansException ex) {
  44. if (logger.isWarnEnabled()) {
  45. logger.warn( "Exception encountered during context initialization - " +
  46. "cancelling refresh attempt: " + ex);
  47. }
  48. // Destroy already created singletons to avoid dangling resources.
  49. destroyBeans();
  50. // Reset 'active' flag.
  51. cancelRefresh(ex);
  52. // Propagate exception to caller.
  53. throw ex;
  54. }
  55. finally {
  56. // Reset common introspection caches in Spring's core, since we
  57. // might not ever need metadata for singleton beans anymore...
  58. resetCommonCaches();
  59. }
  60. }
  61. }

上面refresh()方法的源码,是整个IOC容器初始化的过程。咱们这里讨论的是BeanDefinition的Resource资源的定位,

重点关注refresh()方法中的obtainFreshBeanFactory()方法,该方法也位于AbstractApplicationContext类中。

AbstractApplicationContext.obtainFreshBeanFactory()方法源码:


 
 
  1. protected ConfigurableListableBeanFactory obtainFreshBeanFactory() {
  2. refreshBeanFactory();
  3. ConfigurableListableBeanFactory beanFactory = getBeanFactory();
  4. if (logger.isDebugEnabled()) {
  5. logger.debug( "Bean factory for " + getDisplayName() + ": " + beanFactory);
  6. }
  7. return beanFactory;
  8. }

在上面的obtainFreshBeanFactory()方法中可以看到refreshBeanFactory()方法,是AbstractApplicationContext中的

一个抽象方法,委托给子类具体实现,方法签名如下:

protected abstract void refreshBeanFactory() throws BeansException, IllegalStateException;
 
 

方法的具体实现在AbstractRefreshableApplicationContext中。

AbstractRefreshableApplicationContext.refreshBeanFactory()源码:


 
 
  1. @Override
  2. protected final void refreshBeanFactory() throws BeansException {
  3. // 判断如果已经建立了BeanFactory,则销毁并关闭BeanFactory
  4. if (hasBeanFactory()) {
  5. destroyBeans();
  6. closeBeanFactory();
  7. }
  8. try {
  9. // 创建IoC容器,这里使用的是DefaultListableBeanFactory
  10. DefaultListableBeanFactory beanFactory = createBeanFactory();
  11. // 对IoC容器进行定制化,如设置启动参数,开启注解的自动装配等
  12. beanFactory.setSerializationId(getId());
  13. customizeBeanFactory(beanFactory);
  14. /**
  15. * 启动对BeanDefinition的载入,这里使用了一个委派模式,
  16. * 在当前类中只定义了抽象的loadBeanDefinitions方法,具体的实现调用子类容器
  17. */
  18. loadBeanDefinitions(beanFactory);
  19. synchronized ( this.beanFactoryMonitor) {
  20. this.beanFactory = beanFactory;
  21. }
  22. }
  23. catch (IOException ex) {
  24. throw new ApplicationContextException( "I/O error parsing bean definition source for " + getDisplayName(), ex);
  25. }
  26. }

在refreshBeanFactory()方法中,可以看到loadBeanDefinitions()是AbstractRefreshableApplicationContext中的

一个抽象方法,委托给子类具体实现,方法签名如下:


 
 
  1. protected abstract void loadBeanDefinitions(DefaultListableBeanFactory beanFactory)
  2. throws BeansException, IOException;

loadBeanDefinitions()抽象方法有多个实现:

从FileSystemXmlApplicationContext类图,可以知道选择AbstractXmlApplicationContext中的实现,

因为另外三个与FileSystemXmlApplicationContext没有关系。

AbstractXmlApplicationContext.loadBeanDefinitions()方法源码:


 
 
  1. @Override
  2. protected void loadBeanDefinitions(DefaultListableBeanFactory beanFactory) throws BeansException, IOException {
  3. // Create a new XmlBeanDefinitionReader for the given BeanFactory.
  4. // 根据BeanFactory容器,创建XmlBeanDefinitionReader读取器
  5. XmlBeanDefinitionReader beanDefinitionReader = new XmlBeanDefinitionReader(beanFactory);
  6. // Configure the bean definition reader with this context's
  7. // resource loading environment.
  8. // 使用此上下文的资源加载环境配置Bean定义读取器
  9. beanDefinitionReader.setEnvironment( this.getEnvironment());
  10. beanDefinitionReader.setResourceLoader( this);
  11. beanDefinitionReader.setEntityResolver( new ResourceEntityResolver( this));
  12. // Allow a subclass to provide custom initialization of the reader,
  13. // then proceed with actually loading the bean definitions.
  14. // 允许子类提供读取器的自定义初始化,然后继续加载bean定义信息
  15. initBeanDefinitionReader(beanDefinitionReader);
  16. loadBeanDefinitions(beanDefinitionReader);
  17. }

继续调用loadBeanDefinitions(),咱们现在目标就是定位BeanDEfinition的Resource看下方法源码:


 
 
  1. protected void loadBeanDefinitions(XmlBeanDefinitionReader reader)
  2. throws BeansException, IOException {
  3. // 以Resource的方式获得配置文件的资源位置
  4. Resource[] configResources = getConfigResources();
  5. if (configResources != null) {
  6. reader.loadBeanDefinitions(configResources);
  7. }
  8. // 以String的形式获得配置文件位置
  9. String[] configLocations = getConfigLocations();
  10. if (configLocations != null) {
  11. reader.loadBeanDefinitions(configLocations);
  12. }
  13. }

对于FileSystemXmlApplicationContext会走第二个if判断, 接着看源码。

AbstractBeanDefinitionReader.loadBeanDefinitions()方法源码:


 
 
  1. @Override
  2. public int loadBeanDefinitions(String... locations) throws BeanDefinitionStoreException {
  3. // 如果locations为空,则停止Resource资源定位
  4. Assert.notNull(locations, "Location array must not be null");
  5. int counter = 0;
  6. for (String location : locations) {
  7. // 根据路径载入信息
  8. counter += loadBeanDefinitions(location);
  9. }
  10. return counter;
  11. }

loadBeanDefinitions()方法继续深入:


 
 
  1. public int loadBeanDefinitions(String location, Set<Resource> actualResources) throws BeanDefinitionStoreException {
  2. // 这里得到当前定义的ResourceLoader,默认的使用DefaultResourceLoader
  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. * 这里对Resource的路径模式进行解析,得到需要的Resource集合,
  10. * 这些Resource集合指向了我们定义好的BeanDefinition的信息,可以是多个文件。
  11. */
  12. if (resourceLoader instanceof ResourcePatternResolver) {
  13. // Resource pattern matching available.
  14. try {
  15. // 调用DefaultResourceLoader的getResources完成具体的Resource定位
  16. Resource[] resources = ((ResourcePatternResolver) resourceLoader).getResources(location);
  17. int loadCount = loadBeanDefinitions(resources);
  18. if (actualResources != null) {
  19. for (Resource resource : resources) {
  20. actualResources.add(resource);
  21. }
  22. }
  23. if (logger.isDebugEnabled()) {
  24. logger.debug( "Loaded " + loadCount + " bean definitions from location pattern [" + location + "]");
  25. }
  26. return loadCount;
  27. }
  28. catch (IOException ex) {
  29. throw new BeanDefinitionStoreException(
  30. "Could not resolve bean definition resource pattern [" + location + "]", ex);
  31. }
  32. }
  33. else {
  34. // Can only load single resources by absolute URL.
  35. // 通过ResourceLoader来完成位置定位
  36. Resource resource = resourceLoader.getResource(location);
  37. int loadCount = loadBeanDefinitions(resource);
  38. if (actualResources != null) {
  39. actualResources.add(resource);
  40. }
  41. if (logger.isDebugEnabled()) {
  42. logger.debug( "Loaded " + loadCount + " bean definitions from location [" + location + "]");
  43. }
  44. return loadCount;
  45. }
  46. }

ResourceLoader是一个接口类,其getResource()方法具体实现在DefaultResourceLoader,对于取得Resource的具体过程,

我们可以看下DefaultResourceLoader中getResource()方法的实现。

DefaultResourceLoader.getResource()源码:


 
 
  1. public Resource getResource(String location) {
  2. Assert.notNull(location, "Location must not be null");
  3. Iterator var2 = this.protocolResolvers.iterator();
  4. Resource resource;
  5. do {
  6. if (!var2.hasNext()) {
  7. // 处理所有/标识的Resource
  8. if (location.startsWith( "/")) {
  9. return this.getResourceByPath(location);
  10. }
  11. // 处理所有带有classpath标识的Resource
  12. if (location.startsWith( "classpath:")) {
  13. return new ClassPathResource(location.substring( "classpath:".length()), this.getClassLoader());
  14. }
  15. try {
  16. // 处理URL标识的Resource定位
  17. URL url = new URL(location);
  18. return new UrlResource(url);
  19. } catch (MalformedURLException var5) {
  20. return this.getResourceByPath(location);
  21. }
  22. }
  23. ProtocolResolver protocolResolver = (ProtocolResolver)var2.next();
  24. resource = protocolResolver.resolve(location, this);
  25. } while(resource == null);
  26. return resource;
  27. }

在getResources()方法中,最显眼的是getResourceByPath()方法,在一开始的时候提到过,它是一个模板方法,

DefaultResourceLoader.getResourceByPath()源码:


 
 
  1. protected Resource getResourceByPath(String path) {
  2. return new ClassPathContextResource(path, getClassLoader());
  3. }

DefaultResourceLoader.getResourceByPath()实现类:

其中一个实现类就是FileSystemXmlApplicationContext,其方法签名如下:


 
 
  1. @Override
  2. protected Resource getResourceByPath(String path) {
  3. if (path != null && path.startsWith( "/")) {
  4. path = path.substring( 1);
  5. }
  6. return new FileSystemResource(path);
  7. }

通过该方法,返回一个FileSystemResource对象,该对象扩展自Resource,而Resource扩展自InputStreamSource。

FileSystemResource构造器:


 
 
  1. public FileSystemResource(String path) {
  2. Assert.notNull(path, "Path must not be null");
  3. this.file = new File(path);
  4. this.path = StringUtils.cleanPath(path);
  5. }

FileSystemResource类图:

 

getResourceByPath方法调用过程:

通过FileSystemResource对象,Spring可以进行相关的I/O操作,完成BeanDefinition的Resource定位过程

    这里只是分析了FileSystemXmlApplicationContext的容器下Resource定位过程,

如果是其他的ApplicationContext,那么对应生成其他的Resource,比如ClassPathResource、

ServletContextResource等。关于Spring中Resource的种类,继承关系如下:

这些接口对应不同的Resource实现代表着不同的一样。

    以FileSystemXmlApplicationContext容器实现原理为例,上面只是分析了BeanDefinition的Resource定位过程,

这个时候可以通过Resource对象来进行BeanDefinition的载入了。这里完成了水桶装水找水的过程,下一篇分析一下

水桶装水的过程,也即BeanDefinition的载入和解析过程。

参考文献:

1、《Spring技术内幕》

2、《Spring实战》

3、Spring官网API

4、Spring源码

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值