从源码角度解读 xml 文件中的 xmlns、xsi、xsd

xml 文件中的 xmlns、xsi、xsd

下面是 spring.xml 中的一段:

<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
       xmlns:context="http://www.springframework.org/schema/context"
       xsi:schemaLocation="
       http://www.springframework.org/schema/beans
	   http://www.springframework.org/schema/beans/spring-beans.xsd
       http://www.springframework.org/schema/context
       http://www.springframework.org/schema/context/spring-context.xsd">
  • xmlns:xml namespace,xml 命名空间
  • xsi:xml schema instance,xml 模式实例
  • xsd:xml schema definition,xml 模式定义

一个 xml 文件里至少包含 xmlns、xmlns:xsi 和 xsi:schemaLocation,如 pom.xml:

<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="
         http://maven.apache.org/POM/4.0.0
         http://maven.apache.org/xsd/maven-4.0.0.xsd">

xmlns

xml namespace,xml 命名空间

对比上面的 spring.xml 和 pom.xml,我们就可以知道

  1. xmlns= (不加其它的东西)后面配置的是能当前 xml 的骨架标签
    如 spring.xml 里的 < beans > 和 < bean > 等。
    如 pom.xml 里的 < project > 和 < dependence > 等。
  2. xmlns: 后面配置的是我们能够使用的除了骨架标签以外的其它标签
    如 xsi,这是最特殊的一个,下面具体讲。
    如 context,它使你可以配置 <context:component-scan base-package=“com.xxx”>

xmlns:context="http://www.springframework.org/schema/context" 来举例子,它其实对应的是这个文件
在这里插入图片描述
里的这个处理类
在这里插入图片描述
这个处理类是这样的
在这里插入图片描述
它的初始化其实是把,< context > 标签后面 : 接的元素名 与对应的解析器放到了一个名叫 parsers 的 HashMap 里:
在这里插入图片描述
在这里插入图片描述
BeanDefinitionParser 的作用,就是把一个一个配置转换成 BeanDefinition。
BeanDefinition 就是一个关于 Bean 的信息的类,它包含了这个 Bean 实例化中需要的各种属性,是十分重要的一个类。

而 context:component-scan,注定了

<context:component-scan base-package="com.xx">
    </context:component-scan>

这个名叫 context 的 bean 会用于扫描 @Component。

xsi

xml schema instance,xml 模式实例

为什么叫模式实例,因为标签的解析方式并不是只有一种,你自己也可以定义 < beans >标签的含义,所以我们需要确定我们用的是那种实例。

xmlns:xsi= 后面配置的基本都一样,都是 “http://www.w3.org/2001/XMLSchema-instance”,因为我们配置xmlns:xsi,都是为了能够使用 xsi:schemaLocation。

而使用 xsi:schemaLocation 是为了能够配置所有的 xmlns 后面的 URI 与实际的 xsd 文件的对应关系(所以它们成对出现)。
当然这包括 xmlns= 后面的 URI。
当然这包括 xmlns:xsi 后面的 URI,因为人无法通过抓自己头发的方式把自己提起来(人只能提起其它东西)。

那么,什么是 xsd 文件呢?

xsd

xml schema definition,xml 模式定义

定义,就是定义这个标签该怎么用,不能有其它作用。

它其实在这里对应它的实际文件:
在这里插入图片描述

在这里插入图片描述
打开 org/springframework/context/config/spring-context.xsd,里面其实定义的是标签的规范,如
在这里插入图片描述
这有配置了这些,你才能使用 component-scan。

希望这些对你有所帮助!

发布了130 篇原创文章 · 获赞 233 · 访问量 1万+

猜你喜欢

转载自blog.csdn.net/weixin_44367006/article/details/103651272