Spring 如何从类路径中找到 XSD 文件

How Spring finds the XSD file from classpath

在我们的 spring 配置中,我们将 beans 标签放置如下:

<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">

现在 spring 必须从我的 calsspath 中找出文件 spring-beans.xsd & spring-context.xsd.

的位置

我在这个路径找到了一些 xsd 个文件:

spring-context-4.1.5.RELEASE.jar/org/springframework/context/config

spring-context-2.5.xsd
spring-context-3.0.xsd
spring-context-3.1.xsd
spring-context-3.2.xsd
spring-context-4.0.xsd
spring-context-4.1.xsd

在搜索 spring-beans.xsd 文件时,我在这个路径中找到了一些文件:

spring-beans-4.1.5.RELEASE.jar/org/springframework/beans/factory/xml

spring-beans-2.5.xsd
spring-beans-3.0.xsd
spring-beans-3.1.xsd
spring-beans-3.2.xsd
spring-beans-4.0.xsd
spring-beans-4.1.xsd

spring 如何知道在何处查找此文件,因为在我的 beans 标记中的架构位置与此文件的实际位置之间没有 link。我也能够找到这样的文件 spring-beans-<version>.xsd 然后 spring 如何知道什么是 spring-beans.xsd 即使我们没有在 <beans> 标签中指定任何版本。

一些 spring 库包含一些文件,例如 META-INF/spring.schemas

The properties file called 'spring.schemas' contains a mapping of XML Schema locations (referred to along with the schema declaration in XML files that use the schema as part of the 'xsi:schemaLocation' attribute) to classpath resources. This file is needed to prevent Spring from absolutely having to use a default EntityResolver that requires Internet access to retrieve the schema file. If you specify the mapping in this properties file, Spring will search for the schema on the classpath

例如

spring.schemas of spring-beans-x.x.x-RELEASE.jar

http\://www.springframework.org/schema/beans/spring-beans-2.0.xsd=org/springframework/beans/factory/xml/spring-beans-2.0.xsd
http\://www.springframework.org/schema/beans/spring-beans-2.5.xsd=org/springframework/beans/factory/xml/spring-beans-2.5.xsd
http\://www.springframework.org/schema/beans/spring-beans-3.0.xsd=org/springframework/beans/factory/xml/spring-beans-3.0.xsd
http\://www.springframework.org/schema/beans/spring-beans-3.1.xsd=org/springframework/beans/factory/xml/spring-beans-3.1.xsd
http\://www.springframework.org/schema/beans/spring-beans-3.2.xsd=org/springframework/beans/factory/xml/spring-beans-3.2.xsd
http\://www.springframework.org/schema/beans/spring-beans.xsd=org/springframework/beans/factory/xml/spring-beans-3.2.xsd

简而言之,以上属性允许它将 XSD 资源映射到 schemaLocation 属性。

有关详细信息,另请参阅 Need understanding of spring.handlers and spring.schemas