在使用spring框架的时候,对于其配置文件xml,只是知道其使用方法,而不知道为什么。
这里来研究一下下。
1.配置文件示例
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
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
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop.xsd ">
</beans>
上面是我们最常用的 applicationContext.xml
的配置文件的头部,很多时候我们只是知道这些必须添加,但为什么,添加哪些都不知道。
我们知道spring在启动的时候会验证 xml文档,这些引入的schema即用来验证配置文件的xml文档语法的正确性。
下面先来看看如何验证xml文档验证的相关知识。
2.xml的schema约束
schema定义
Schema的作用是定义一份XML文档中的可以正确使用的标签组。
就像文档类型定义(document type declaration 外语缩写:DTD)的作用一样,一份XML Schema定义了:
- 可以出现在文档里的元素;
- 可以出现在文档里的属性;
- 哪些元素是子元素;
- 子元素的顺序;
- 子元素的数量;
- 一个元素应是否能包含文本,或应该是空的;
- 元素和属性的数据类型;
- 元素和属性的默认值和固定值。
XML Schema 是 DTD 的升级版
XML Schema 是用来取代 DTD 的 。
XML Schema 优于DTD的地方:
- XML Schema 可针对未来的需求进行扩展
- XML Schema 更完善,功能更强大
- XML Schema 基于 XML 编写
- XML Schema 支持数据类型
- XML Schema 支持命名空间
先来说说xml文档的schema约束,它定义了xml文档的结构,内容和语法,包括元素和属性、关系的结构以及数据类型等。
有以下几点需要遵循:
所有的标签和属性都需要Schema来定义。(schema本身由w3c来定义)。
所有的schema文件都需要以个ID,这里我们称之为 namespace,其值时一个url,通常是这个xml的xsd文件的地址。
namespace值由 targetNamespace 属性来指定
引入一个schema约束,使用属性xmlns,属性值即为对应schema文件的命名空间 nameSpace。
如果引入的schema非w3c组织定义的,必须指定schema文件的位置,schema文件的位置由 schemaLocation来指定。
引入多个schema文件需要使用别名。别名形式如下: xmlns:alias。
3.配置文件的详细解读
标签 | 说明 |
---|---|
xmlns | xml NameSpace : xml文件命名空间 |
xsi | xml schema instance : xml Schema 实例 |
xsi:schemaLocation | 指定命名空间 + Schema文件的位置 |
xmlns:alias | xmlns:alias : 命名空间的别名 |
声明默认的名称空间(
xmlns="http://www.springframework.org/schema/beans"
)声明XML Schema实例名称空间(
http://www.w3.o