热门标签 | HotTags
当前位置:  开发笔记 > 编程语言 > 正文

Spring通过<import>标签导入外部配置文件

之前文章里我们讲到Spring加载Xml配置文件的细节,那么加载完了我们肯定要解析这个配置文件中定义的元素。这篇我们首先来分析下Spring是如何通过标签

Spring通过<import>标签导入外部配置文件

示例

我们先来看下配置文件是怎么导入外部配置文件的?先定义一个spring-import配置文件如下:

<&#63;xml version="1.0" encoding="UTF-8"&#63;>

   
   
   

我们看到里面定义了一个标签并用属性resource声明了导入的资源文件为spring-config.xml。我们再来看下spring-config.xml配置文件是怎样的:

<&#63;xml version="1.0" encoding="UTF-8"&#63;>

   
          
            
   
   
      
      
   

然后我们可以实例化一个BeanFactory来加载spring-import这个配置文件了。

public static void main(String[] args) {
   ApplicationContext cOntext=new ClassPathXmlApplicationContext("spring-import.xml");
   Person outerPerson=(Person)context.getBean("outerPerson");
   System.out.println(outerPerson);
}

如果没问题的话,我们可以获取到outerPerson这个bean并打印了。

Person [0, john wonder]

原理

我们来通过源码分析下Spring是如何解析import标签并加载这个导入的配置文件的。首先我们到DefaultBeanDefinitionDocumentReader类中看下:

DefaultBeanDefinitionDocumentReader

我们可以看到类里面定义了一个public static final 的IMPORT_ELEMENT变量:

public static final String IMPORT_ELEMENT = "import";

然后我们可以搜索下哪边用到了这个变量,并且定位到parseDefaultElement函数:

parseDefaultElement

private void parseDefaultElement(Element ele, BeanDefinitionParserDelegate delegate) {
   //todo  对 import 标签的解析 2020-11-17
   if (delegate.nodeNameEquals(ele, IMPORT_ELEMENT)) {
      importBeanDefinitionResource(ele);
   }
}

这里就是我们要找的导入外部配置文件加载Bean定义的源代码,我们再重点看下importBeanDefinitionResource函数:

importBeanDefinitionResource

/**
 * Parse an "import" element and load the bean definitions
 * from the given resource into the bean factory.
 */
protected void importBeanDefinitionResource(Element ele) {
   //// 获取 resource 的属性值
   String location = ele.getAttribute(RESOURCE_ATTRIBUTE);
   //// 为空,直接退出
   if (!StringUtils.hasText(location)) {
      getReaderContext().error("Resource location must not be empty", ele);
      return;
   }
   // Resolve system properties: e.g. "${user.dir}"
   // // 解析系统属性,格式如 :"${user.dir}"
   location = getReaderContext().getEnvironment().resolveRequiredPlaceholders(location);
   Set actualResources = new LinkedHashSet<>(4);
   // Discover whether the location is an absolute or relative URI
   //// 判断 location 是相对路径还是绝对路径
   boolean absoluteLocation = false;
   try {
      //以 classpath*: 或者 classpath: 开头为绝对路径
      absoluteLocation = ResourcePatternUtils.isUrl(location) || ResourceUtils.toURI(location).isAbsolute();
   }
   catch (URISyntaxException ex) {
      // cannot convert to an URI, considering the location relative
      // unless it is the well-known Spring prefix "classpath*:"
   }

   // Absolute or relative&#63;
   //绝对路径 也会调用loadBeanDefinitions
   if (absoluteLocation) {
      try {
         int importCount = getReaderContext().getReader().loadBeanDefinitions(location, actualResources);
         if (logger.isTraceEnabled()) {
            logger.trace("Imported " + importCount + " bean definitions from URL location [" + location + "]");
         }
      }
      catch (BeanDefinitionStoreException ex) {
         getReaderContext().error(
               "Failed to import bean definitions from URL location [" + location + "]", ele, ex);
      }
   }
   else {
      //如果是相对路径,则先计算出绝对路径得到 Resource,然后进行解析
      // No URL -> considering resource location as relative to the current file.
      try {
         int importCount;
         Resource relativeResource = getReaderContext().getResource().createRelative(location);

         //如果相对路径 这个资源存在 那么就加载这个bean 定义
         if (relativeResource.exists()) {
            importCount = getReaderContext().getReader().loadBeanDefinitions(relativeResource);
            actualResources.add(relativeResource);
         }
         else {
            String baseLocation = getReaderContext().getResource().getURL().toString();
            //todo import节点 内部会调用loadBeanDefinitions 操作 2020-10-17
            importCount = getReaderContext().getReader().loadBeanDefinitions(
                  StringUtils.applyRelativePath(baseLocation, location), actualResources);
         }
         if (logger.isTraceEnabled()) {
            logger.trace("Imported " + importCount + " bean definitions from relative location [" + location + "]");
         }
      }
   }
}

我们来解析下这段代码是怎么一个流程:

1.首先通过resource标签解析到它的属性值,并且判读字符串值是否为空。

2.接下来它还会通过当前上下文环境去解析字符串路径里面的占位符,这点我们在之前文章中分析过。

2.接下来判断是否是绝对路径,通过调用ResourcePatternUtils.isUrl(location) || ResourceUtils.toURI(location).isAbsolute();来判断,划重点:以 classpath*: 或者 classpath: 开头为绝对路径,或者可以生成一个URI实例就是当作绝对路径,或者也可以URI的isAbsolute来判断

3.如果是绝对路径那么我们通过getReaderContext().getReader()获取到XmlBeanDefinitionReader然后调用它的loadBeanDefinitions(String location, @Nullable Set actualResources)函数

4.如果不是绝对路径那么我们尝试生成相对当前资源的路径(这点很重要),再通过loadBeanDefinitions方法来加载这个配置文件中的BeanDefinitions。这里有个细节需要我们注意,就是它为什么要尝试去判断资源是否存在?就是如果存在的话那么直接调用loadBeanDefinitions(Resource resource)方法,也就是说这里肯定是加载单个资源文件,如方法注释所说:

/**
 * Load bean definitions from the specified XML file.
 * @param resource the resource descriptor for the XML file
 * @return the number of bean definitions found
 * @throws BeanDefinitionStoreException in case of loading or parsing errors
 */
@Override
public int loadBeanDefinitions(Resource resource) throws BeanDefinitionStoreException {
   //load中去注册BeanDefinition
   return loadBeanDefinitions(new EncodedResource(resource));
}

从指定的xml文件加载Bean定义。如果不存在,那么就跟绝对路径一样会调用loadBeanDefinitions(String location, @Nullable Set actualResources)函数,我们来看看这个函数的定义:

/**
 * Load bean definitions from the specified resource location.
 * 

The location can also be a location pattern, provided that the * ResourceLoader of this bean definition reader is a ResourcePatternResolver. * @param location the resource location, to be loaded with the ResourceLoader * (or ResourcePatternResolver) of this bean definition reader * @param actualResources a Set to be filled with the actual Resource objects * that have been resolved during the loading process(要填充加载过程中已解析的实际资源对象*的集合). May be {@code null} * to indicate that the caller is not interested in those Resource objects. */ public int loadBeanDefinitions(String location, @Nullable Set actualResources) throws BeanDefinitionStoreException {

解释很清楚,这个location是指从指定资源路径加载BeanDefinitions。

总结

从源码可以看出从外部导入配置文件也就是给了通过一个总的配置文件来加载各个单一配置文件扩展的机会。

以上就是Spring通过标签导入外部配置文件的详细内容,更多关于Spring 导入外部配置文件的资料请关注编程笔记其它相关文章!


推荐阅读
  • 在Xamarin XAML语言中如何在页面级别构建ControlTemplate控件模板
    本文介绍了在Xamarin XAML语言中如何在页面级别构建ControlTemplate控件模板的方法和步骤,包括将ResourceDictionary添加到页面中以及在ResourceDictionary中实现模板的构建。通过本文的阅读,读者可以了解到在Xamarin XAML语言中构建控件模板的具体操作步骤和语法形式。 ... [详细]
  • Spring源码解密之默认标签的解析方式分析
    本文分析了Spring源码解密中默认标签的解析方式。通过对命名空间的判断,区分默认命名空间和自定义命名空间,并采用不同的解析方式。其中,bean标签的解析最为复杂和重要。 ... [详细]
  • Spring学习(4):Spring管理对象之间的关联关系
    本文是关于Spring学习的第四篇文章,讲述了Spring框架中管理对象之间的关联关系。文章介绍了MessageService类和MessagePrinter类的实现,并解释了它们之间的关联关系。通过学习本文,读者可以了解Spring框架中对象之间的关联关系的概念和实现方式。 ... [详细]
  • Iamtryingtomakeaclassthatwillreadatextfileofnamesintoanarray,thenreturnthatarra ... [详细]
  • 本文讨论了在Spring 3.1中,数据源未能自动连接到@Configuration类的错误原因,并提供了解决方法。作者发现了错误的原因,并在代码中手动定义了PersistenceAnnotationBeanPostProcessor。作者删除了该定义后,问题得到解决。此外,作者还指出了默认的PersistenceAnnotationBeanPostProcessor的注册方式,并提供了自定义该bean定义的方法。 ... [详细]
  • Spring特性实现接口多类的动态调用详解
    本文详细介绍了如何使用Spring特性实现接口多类的动态调用。通过对Spring IoC容器的基础类BeanFactory和ApplicationContext的介绍,以及getBeansOfType方法的应用,解决了在实际工作中遇到的接口及多个实现类的问题。同时,文章还提到了SPI使用的不便之处,并介绍了借助ApplicationContext实现需求的方法。阅读本文,你将了解到Spring特性的实现原理和实际应用方式。 ... [详细]
  • 本文讨论了一个关于cuowu类的问题,作者在使用cuowu类时遇到了错误提示和使用AdjustmentListener的问题。文章提供了16个解决方案,并给出了两个可能导致错误的原因。 ... [详细]
  • XML介绍与使用的概述及标签规则
    本文介绍了XML的基本概念和用途,包括XML的可扩展性和标签的自定义特性。同时还详细解释了XML标签的规则,包括标签的尖括号和合法标识符的组成,标签必须成对出现的原则以及特殊标签的使用方法。通过本文的阅读,读者可以对XML的基本知识有一个全面的了解。 ... [详细]
  • Android开发实现的计时器功能示例
    本文分享了Android开发实现的计时器功能示例,包括效果图、布局和按钮的使用。通过使用Chronometer控件,可以实现计时器功能。该示例适用于Android平台,供开发者参考。 ... [详细]
  • Java SE从入门到放弃(三)的逻辑运算符详解
    本文详细介绍了Java SE中的逻辑运算符,包括逻辑运算符的操作和运算结果,以及与运算符的不同之处。通过代码演示,展示了逻辑运算符的使用方法和注意事项。文章以Java SE从入门到放弃(三)为背景,对逻辑运算符进行了深入的解析。 ... [详细]
  • 本文介绍了在Java中gt、gtgt、gtgtgt和lt之间的区别。通过解释符号的含义和使用例子,帮助读者理解这些符号在二进制表示和移位操作中的作用。同时,文章还提到了负数的补码表示和移位操作的限制。 ... [详细]
  • 后台获取视图对应的字符串
    1.帮助类后台获取视图对应的字符串publicclassViewHelper{将View输出为字符串(注:不会执行对应的ac ... [详细]
  • 本文详细介绍了Java中vector的使用方法和相关知识,包括vector类的功能、构造方法和使用注意事项。通过使用vector类,可以方便地实现动态数组的功能,并且可以随意插入不同类型的对象,进行查找、插入和删除操作。这篇文章对于需要频繁进行查找、插入和删除操作的情况下,使用vector类是一个很好的选择。 ... [详细]
  • 本文介绍了南邮ctf-web的writeup,包括签到题和md5 collision。在CTF比赛和渗透测试中,可以通过查看源代码、代码注释、页面隐藏元素、超链接和HTTP响应头部来寻找flag或提示信息。利用PHP弱类型,可以发现md5('QNKCDZO')='0e830400451993494058024219903391'和md5('240610708')='0e462097431906509019562988736854'。 ... [详细]
  • iOS超签签名服务器搭建及其优劣势
    本文介绍了搭建iOS超签签名服务器的原因和优势,包括不掉签、用户可以直接安装不需要信任、体验好等。同时也提到了超签的劣势,即一个证书只能安装100个,成本较高。文章还详细介绍了超签的实现原理,包括用户请求服务器安装mobileconfig文件、服务器调用苹果接口添加udid等步骤。最后,还提到了生成mobileconfig文件和导出AppleWorldwideDeveloperRelationsCertificationAuthority证书的方法。 ... [详细]
author-avatar
手机用户2602899031
这个家伙很懒,什么也没留下!
PHP1.CN | 中国最专业的PHP中文社区 | DevBox开发工具箱 | json解析格式化 |PHP资讯 | PHP教程 | 数据库技术 | 服务器技术 | 前端开发技术 | PHP框架 | 开发工具 | 在线工具
Copyright © 1998 - 2020 PHP1.CN. All Rights Reserved | 京公网安备 11010802041100号 | 京ICP备19059560号-4 | PHP1.CN 第一PHP社区 版权所有