本文从自定义spring配置文件入手,介绍了spring配置文件头的原理,和spring.schema、spring.handlers两个文件的作用。
下面是一个简单的spring配置文件。我们可以看到,xml文件的前几行这些配置,其实都是xml 结构的定义,通过引入这些定义,使xml文件中的标签可以正常被spring解析。
<?xml version="1.0" encoding="UTF-8"?>
<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">
<context:annotation-config/>
</beans>
那么这些代码是什么含义?spring是如何解析这些配置文件的?我们能否轻松解析自定义的xml配置文件呢?本篇文章或许能够帮你解答疑惑。
1.XML文件头
xml文件的头部位置是用来对验证模式进行声明的,以保证文件的正确性。xml文件的验证模式常见的有两种,一种是DTD(文档类型定义)和XSD(XML Schema)。DTD因为其不可扩展、不支持命名空间等缺陷,逐渐被XSD所淘汰,目前主流框架如maven、spring等使用的xml配置文件的验证模式都是XSD模式,因此在此不再赘述DTD。
XSD是基于xml语法进行编写的验证文件,通过xsd文件,我们可以进行xml标签的自定义。XSD模式的优点在此不再赘述,网上有很多,总结下来,就是XSD模式更灵活、更兼容、更简单。
对XSD的使用,我们可以分为两部分,XSD的定义以及XSD的引用。
1.1 XSD的定义
所谓定义XSD,即定义一个xml文件的使用模式,这里面定义了以下内容:
- xml文档中使用的标签元素
- 标签元素对应的属性
- 标签元素及其属性的类型
- 标签元素的子元素,包括子元素的类型、数目、次序
- 标签元素的默认类型和默认值
这个是spring-beans的xsd文件的一部分:
<!-- Top-level <beans> tag -->
<xsd:element name="beans">
<xsd:annotation>
<xsd:documentation><![CDATA[
Container for <bean> and other elements, typically the root element in the document.
Allows the definition of default values for all nested bean definitions. May itself
be nested for the purpose of defining a subset of beans with certain default values or
to be registered only when certain profile(s) are active. Any such nested <beans> element
must be declared as the last element in the document.
]]></xsd:documentation>
</xsd:annotation>
<xsd:complexType>
<xsd:sequence>
<xsd:element ref="description" minOccurs="0"/>
<xsd:choice minOccurs="0" maxOccurs="unbounded">
<xsd:element ref="import"/>
<xsd:element ref="alias"/>
<xsd:element ref="bean"/>
<xsd:any namespace="##other" processContents="strict" minOccurs="0" maxOccurs="unbounded"/>
</xsd:choice>
<xsd:element ref="beans" minOccurs="0" maxOccurs="unbounded"/>