Spring XmlBeanFactory 容器的基本实现

鼠扑  金牌会员 | 2022-8-22 01:09:29 | 显示全部楼层 | 阅读模式
打印 上一主题 下一主题

主题 926|帖子 926|积分 2778

容器的基本用法

熟悉 Spring 的朋友应该都很了解下段代码:
  1. public void testBeanFactory() {
  2.         BeanFactory bf = new XmlBeanFactory(new ClassPathResource("beanFactoryTest.xml"));
  3.     TestBean testBean = bf.getBean("testBean");
  4. }
复制代码
一段简单的通过容器获取 Bean 的代码,它所完成的功能无非就是以下几点:

  • 读取配置文件 beanFactoryTest.xml
  • 根据 beanFactoryTest.xml 中的配置找到对应类的配置,并实例化
  • 获取实例化后的实例
接下来我们来分析这段代码的实现原理

Spring 核心类介绍

在开始正式的源码分析之前,有必要先了解 Spring 核心的两个类
1. DefaultListableBeanFactory

XmlBeanFactory 继承自 DefaultListableBeanFactory,DefaultListableBeanFactory 是整个 bean 加载的核心部分,是 Spring 注册及加载 bean 的默认实现。XmlBeanFactory 与 DefaultListableBeanFactory 的不同之处就在于 XmlBeanFactory 使用了自定义的 XML 读取器 XmlBeanDefinitionReader
2. XmlBeanDefinitionReader

在 XmlBeanDefinitionReader 中主要包含以下几步处理:

  • 通过继承自 AbstractBeanDefinitionReader 的方法,使用 ResourceLoader 将资源文件路径转换为对应的 Resoure 文件
  • 通过 DocumentLoader 对 Resource 文件进行转换,将 Resource 文件转换为 Document 文件
  • 通过实现 BeanDefinitionDocumentReader 的 DefaultBeanDefinitionDocumentReader 类对 Document 进行解析,并使用 BeanDefinitionParserDelegate 对 Element 进行解析

容器基础 XmlBeanFactory

接下来我们将深入分析以下代码的功能实现
  1. BeanFactory bf = new XmlBeanFactory(new ClassPathResource("beanFactoryTest.xml"));
复制代码
通过 XmlBeanFactory 初始化时序图,我们来看一看上面代码的执行逻辑

1. 封装配置文件

Spring 的配置文件读取是通过 ClassPathResource 封装成 Resource,Resource 的结构如下:
  1. public interface Resource extends InputStreamSource {
  2.     boolean exists();
  3.     default boolean isReadable() {
  4.         return this.exists();
  5.     }
  6.     default boolean isOpen() {
  7.         return false;
  8.     }
  9.     default boolean isFile() {
  10.         return false;
  11.     }
  12.     URL getURL() throws IOException;
  13.     URI getURI() throws IOException;
  14.     File getFile() throws IOException;
  15.     default ReadableByteChannel readableChannel() throws IOException {
  16.         return Channels.newChannel(this.getInputStream());
  17.     }
  18.     long contentLength() throws IOException;
  19.     long lastModified() throws IOException;
  20.     Resource createRelative(String var1) throws IOException;
  21.     @Nullable
  22.     String getFilename();
  23.     String getDescription();
  24. }
复制代码
Resource 接口抽象了所有 Spring 内部使用的底层资源:File、URL、Classpath 等等,并定义了有关资源操作的方法。对于不同来源的资源文件,都有对应的 Resource 实现:文件(FileSystemResource)、Classpath(ClasspathResource)、URL(UrlResource )、InputStream(InputStreamResource)、Byte(ByteResource)等等,有了 Resource 接口就可以对所有资源文件进行统一处理,至于处理的实现其实很简单,以 ClasspathResource 为例,实现方式就是通过 class 或者 classLoader 提供的底层方式进行调用
2. 数据准备阶段

通过 Resource 完成配置文件的封装以后,就将 Resource 作为 XmlBeanFactory 的构造函数参数传入,代码如下:
  1. public XmlBeanFactory(Resource resource) throws BeansException {
  2.     this(resource, (BeanFactory)null);
  3. }
复制代码
构造函数内部再次调用内部构造函数:
  1. public XmlBeanFactory(Resource resource, BeanFactory parentBeanFactory) throws BeansException {
  2.     super(parentBeanFactory);
  3.     this.reader = new XmlBeanDefinitionReader(this);
  4.     this.reader.loadBeanDefinitions(resource);
  5. }
复制代码
this.reader.loadBeanDefinitions(resource); 是整个资源加载的切入点,这个方法的处理过程如下:

  • 对参数 Resource 使用 EncodedResource 类进行封装
  • 从 Resource 获取对应的 InputStream 并构造 InputSource
  • 通过构造的 InputSource 实例和 Resource 实例继续调用函数 doLoadBeanDefinitions
我们来看一下 loadBeanDefinitions 函数具体的实现过程:
  1. public int loadBeanDefinitions(Resource resource) throws BeanDefinitionStoreException {
  2.     return this.loadBeanDefinitions(new EncodedResource(resource));
  3. }
复制代码
EncodedResource 的作用是对资源文件的编码进行处理,可以通过设置编码属性指定 Spring 使用响应的编码进行处理
当构造好 EncodedResource 对象后,再次转入到  loadBeanDefinitions(new EncodedResource(resource));
  1. public int loadBeanDefinitions(EncodedResource encodedResource) throws BeanDefinitionStoreException {
  2.     Assert.notNull(encodedResource, "EncodedResource must not be null");
  3.     if (this.logger.isTraceEnabled()) {
  4.         this.logger.trace("Loading XML bean definitions from " + encodedResource);
  5.     }
  6.         // 获取已经加载的资源
  7.     Set<EncodedResource> currentResources = (Set)this.resourcesCurrentlyBeingLoaded.get();
  8.     if (!currentResources.add(encodedResource)) {
  9.         throw new BeanDefinitionStoreException("Detected cyclic loading of " + encodedResource + " - check your import definitions!");
  10.     } else {
  11.         int var6;
  12.         try {
  13.             // 从已经封装的 Resource 对象获取 InputStream
  14.             InputStream inputStream = encodedResource.getResource().getInputStream();
  15.             Throwable var4 = null;
  16.             try {
  17.                 InputSource inputSource = new InputSource(inputStream);
  18.                 if (encodedResource.getEncoding() != null) {
  19.                     inputSource.setEncoding(encodedResource.getEncoding());
  20.                 }
  21.                                 // 进入真正的逻辑核心部分
  22.                 var6 = this.doLoadBeanDefinitions(inputSource, encodedResource.getResource());
  23.             } catch (Throwable var24) {
  24.                 var4 = var24;
  25.                 throw var24;
  26.             } finally {
  27.                 if (inputStream != null) {
  28.                     if (var4 != null) {
  29.                         try {
  30.                             inputStream.close();
  31.                         } catch (Throwable var23) {
  32.                             var4.addSuppressed(var23);
  33.                         }
  34.                     } else {
  35.                         inputStream.close();
  36.                     }
  37.                 }
  38.             }
  39.         } catch (IOException var26) {
  40.             throw new BeanDefinitionStoreException("IOException parsing XML document from " + encodedResource.getResource(), var26);
  41.         } finally {
  42.             currentResources.remove(encodedResource);
  43.             if (currentResources.isEmpty()) {
  44.                 this.resourcesCurrentlyBeingLoaded.remove();
  45.             }
  46.         }
  47.         return var6;
  48.     }
  49. }
复制代码
再次整理数据准备阶段的逻辑,首先对传入的 Resource 参数进行编码处理,将准备的数据传入到真正的核心处理部分 doLoadBeanDefinitions 方法
3. 获取 Document

doLoadBeanDefinitions 方法的代码如下:
  1. protected int doLoadBeanDefinitions(InputSource inputSource, Resource resource) throws BeanDefinitionStoreException {
  2.     try {
  3.         Document doc = this.doLoadDocument(inputSource, resource);
  4.         int count = this.registerBeanDefinitions(doc, resource);
  5.         if (this.logger.isDebugEnabled()) {
  6.             this.logger.debug("Loaded " + count + " bean definitions from " + resource);
  7.         }
  8.         return count;
  9.     } catch (BeanDefinitionStoreException var5) {
  10.         throw var5;
  11.     } catch (SAXParseException var6) {
  12.         throw new XmlBeanDefinitionStoreException(resource.getDescription(), "Line " + var6.getLineNumber() + " in XML document from " + resource + " is invalid", var6);
  13.     } catch (SAXException var7) {
  14.         throw new XmlBeanDefinitionStoreException(resource.getDescription(), "XML document from " + resource + " is invalid", var7);
  15.     } catch (ParserConfigurationException var8) {
  16.         throw new BeanDefinitionStoreException(resource.getDescription(), "Parser configuration exception parsing XML from " + resource, var8);
  17.     } catch (IOException var9) {
  18.         throw new BeanDefinitionStoreException(resource.getDescription(), "IOException parsing XML document from " + resource, var9);
  19.     } catch (Throwable var10) {
  20.         throw new BeanDefinitionStoreException(resource.getDescription(), "Unexpected exception parsing XML document from " + resource, var10);
  21.     }
  22. }
  23. protected Document doLoadDocument(InputSource inputSource, Resource resource) throws Exception {
  24.     return this.documentLoader.loadDocument(inputSource, this.getEntityResolver(), this.errorHandler, this.getValidationModeForResource(resource), this.isNamespaceAware());
  25. }
复制代码
不考虑处理异常的代码,其实只做了三件事:

  • 获取对 XML 文件的验证模式
  • 加载 XML 文件,并得到对应的 Document
  • 根据返回的 Document 注册 Bean 信息
获取 XML 验证模式是为了保证 XML 文件的正确性,常用的验证模式有 DTD 和 XSD 两种。Spring 通过 getValidationModeForResource 方法获取对应资源的验证模式,这里不再赘述
  1. protected int getValidationModeForResource(Resource resource) {
  2.     int validationModeToUse = this.getValidationMode();
  3.     // 如果手动指定了验证模式就使用指定的验证模式
  4.     if (validationModeToUse != 1) {
  5.         return validationModeToUse;
  6.     } else {
  7.         // 如果未指定就使用自动检测
  8.         int detectedMode = this.detectValidationMode(resource);
  9.         return detectedMode != 1 ? detectedMode : 3;
  10.     }
  11. }
复制代码
XmlBeanDefinitionReader 将文档读取交由 DocumentLoader 去处理,DocumentLoader 是个接口,真正调用的是 DefaultDocumentLoader,解析代码如下:
  1. public Document loadDocument(InputSource inputSource, EntityResolver entityResolver, ErrorHandler errorHandler, int validationMode, boolean namespaceAware) throws Exception {
  2.     DocumentBuilderFactory factory = this.createDocumentBuilderFactory(validationMode, namespaceAware);
  3.     if (logger.isTraceEnabled()) {
  4.         logger.trace("Using JAXP provider [" + factory.getClass().getName() + "]");
  5.     }
  6.     DocumentBuilder builder = this.createDocumentBuilder(factory, entityResolver, errorHandler);
  7.     return builder.parse(inputSource);
  8. }
复制代码
对于这部分代码没有太多可以描述的,因为通过 SAX 解析 XML 文档的套路大都相同,解析完成返回一个 Document 对象
4. 解析及注册 BeanDefinitions

当程序拥有 Document 对象后,就会被引入下面这个方法:
  1. public int registerBeanDefinitions(Document doc, Resource resource) throws BeanDefinitionStoreException {
  2.     // 使用 DefaultBeanDefinitionDocumentReader 实例化 BeanDefinitionDocumentReader
  3.     BeanDefinitionDocumentReader documentReader = this.createBeanDefinitionDocumentReader();
  4.     // 记录统计前 BeanDefinition 的加载个数
  5.     int countBefore = this.getRegistry().getBeanDefinitionCount();
  6.     // 加载及注册 bean
  7.     documentReader.registerBeanDefinitions(doc, this.createReaderContext(resource));
  8.     // 记录本次加载的 BeanDefinition 个数
  9.     return this.getRegistry().getBeanDefinitionCount() - countBefore;
  10. }
复制代码
BeanDefinitionDocumentReader 是一个接口,通过 createBeanDefinitionDocumentReader 方法完成实例化,实际类型是 DefaultBeanDefinitionDocumentReader,registerBeanDefinitions 方法代码如下:
  1. public void registerBeanDefinitions(Document doc, XmlReaderContext readerContext) {
  2.     this.readerContext = readerContext;
  3.     this.doRegisterBeanDefinitions(doc.getDocumentElement());
  4. }
复制代码
getDocumentElement 方法的重要目的之一是提取 root,以便于再次将 root 作为参数继续 BeanDefinition 的注册
再次进入 doRegisterBeanDefinitions 方法:
  1. protected void doRegisterBeanDefinitions(Element root) {
  2.     // 专门处理解析
  3.     BeanDefinitionParserDelegate parent = this.delegate;
  4.     this.delegate = this.createDelegate(this.getReaderContext(), root, parent);
  5.     // 处理 profile 属性
  6.     if (this.delegate.isDefaultNamespace(root)) {
  7.         String profileSpec = root.getAttribute("profile");
  8.         if (StringUtils.hasText(profileSpec)) {
  9.             String[] specifiedProfiles = StringUtils.tokenizeToStringArray(profileSpec, ",; ");
  10.             if (!this.getReaderContext().getEnvironment().acceptsProfiles(specifiedProfiles)) {
  11.                 if (this.logger.isDebugEnabled()) {
  12.                     this.logger.debug("Skipped XML bean definition file due to specified profiles [" + profileSpec + "] not matching: " + this.getReaderContext().getResource());
  13.                 }
  14.                 return;
  15.             }
  16.         }
  17.     }
  18.         // 解析前处理,留给子类实现
  19.     this.preProcessXml(root);
  20.     this.parseBeanDefinitions(root, this.delegate);
  21.     // 解析后处理,留给子类实现
  22.     this.postProcessXml(root);
  23.     this.delegate = parent;
  24. }
复制代码
这里使用了模板方法设计模式,如果继承自 DefaultBeanDefinitionDocumentReader 的子类需要在 Bean 解析前后做一些处理的话,可以重写 preProcessXml 和 postProcessXml 方法
在注册 Bean 的最开始是先对 profile 属性解析,profile 属性可用于在配置文件中部署两套配置分别适用生产环境和开发环境,做到方便的的切换环境
处理完 profile 属性以后就可以进行 XML 的读取,跟踪代码进入 parseBeanDefinitions 方法
  1. protected void parseBeanDefinitions(Element root, BeanDefinitionParserDelegate delegate) {
  2.     if (delegate.isDefaultNamespace(root)) {
  3.         NodeList nl = root.getChildNodes();
  4.         for(int i = 0; i < nl.getLength(); ++i) {
  5.             Node node = nl.item(i);
  6.             if (node instanceof Element) {
  7.                 Element ele = (Element)node;
  8.                 if (delegate.isDefaultNamespace(ele)) {
  9.                     this.parseDefaultElement(ele, delegate);
  10.                 } else {
  11.                     delegate.parseCustomElement(ele);
  12.                 }
  13.             }
  14.         }
  15.     } else {
  16.         delegate.parseCustomElement(root);
  17.     }
  18. }
复制代码
根节点或者子节点是默认命名空间的话采用 parseDefaultElement 方法解析,否则使用 delegate.parseCustomElement 方法解析,而对于标签的解析,我们放到下一篇文章作讲解


免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作!

本帖子中包含更多资源

您需要 登录 才可以下载或查看,没有账号?立即注册

x
回复

使用道具 举报

0 个回复

倒序浏览

快速回复

您需要登录后才可以回帖 登录 or 立即注册

本版积分规则

鼠扑

金牌会员
这个人很懒什么都没写!
快速回复 返回顶部 返回列表