最初Spring配置文件的頭部聲明如下:
Xml代碼
- <?xml version="1.0" encoding="UTF-8"?>
- <!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN 2.0//EN"
- "http://www.springframework.org/dtd/spring-beans-2.0.dtd">
- <beans>
- </beans>
- 說明:
- 1、第一行表示xml聲明,任何格式良好的xml文檔都必須第一行是聲明。相當於告訴解析器這個是xml文檔,你給我用xml解析器解析。
- 2、dtd聲明,表示該xml里的元素和屬性等需符合spring-beans-2.0.dtd這個文檔類型定義標准。
- DTD:文件的文件型別定義(Document Type Definition)可以看成一個或者多個 XML 文件的模板,在這里可以定義 XML 文件中的元素、元素的屬性、元素的排列方式、元素包含的內容等等。
因為DTD的一些局限性,以及XML Schema對數據類型和命名空間的支持。XML Schema很快會將 DTD 取而代之
被XML Schema 取代后的Spring 配置:
Xml代碼
- <?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:aop="http://www.springframework.org/schema/aop"
- xmlns:tx="http://www.springframework.org/schema/tx" xmlns:context="http://www.springframework.org/schema/context"
- xsi:schemaLocation="
- http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
- http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.0.xsd
- http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.0.xsd
- http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd">
- </beans>
- XML Schema命名空間作用:
- 1、避免命名沖突,像Java中的package一樣
- 2、將不同作用的標簽分門別類(像Spring中的tx命名空間針對事務類的標簽,context命名空間針對組件的標簽)
- 代碼解釋:
- 1、xmlns="http://www.springframework.org/schema/beans"
- 聲明xml文件默認的命名空間,表示未使用其他命名空間的所有標簽的默認命名空間。
- 2、xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
- 聲明XML Schema 實例,聲明后就可以使用 schemaLocation 屬性了
- 3、xmlns:aop="http://www.springframework.org/schema/aop"
- 聲明前綴為aop的命名空間,后面的URL用於標示命名空間的地址不會被解析器用於查找信息。其惟一的作用是賦予命名空間一個惟一的名稱。當命名空間被定義在元素的開始標簽中時,所有帶有相同前綴的子元素都會與同一個命名空間相關聯。
- 4、xsi:schemaLocation="
- http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
- 這個從命名可以看出個大概,指定Schema的位置這個屬性必須結合命名空間使用。這個屬性有兩個值,第一個值表示需要使用的命名空間。第二個值表示供命名空間使用的 XML schema 的位置
- 所以我們需要什么樣的標簽的時候,就引入什么樣的命名空間和Schema 定義就可以了。
Spring默認在啟動時是要加載XSD文件來驗證xml文件的,所以如果有的時候斷網了,或者一些開源軟件切換域名,那么就很容易碰到應用啟動不了。我記得當時Oracle收購Sun公司時,遇到過這個情況。為了防止這種情況,Spring提供了一種機制,默認從本地加載XSD文件。打開spring-context-3.2.0.RELEASE.jar,可以看到里面有兩個特別的文件:
spring.handlers
spring.schemas
再打開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是把XSD文件放到本地了,再在spring.schemas里做了一個映射,優先從本地里加載XSD文件。
並且Spring很貼心,把舊版本的XSD文件也全放了。這樣可以防止升級了Spring版本,而配置文件里用的還是舊版本的XSD文件,然后斷網了,應用啟動不了。
我們還可以看到,在沒有配置版本號時,用的就是當前版本的XSD文件:
如何跳過Spring的XML校驗?
可以用這樣的方式來跳過校驗:
如何寫一個自己的spring xml namespace擴展
可以參考Spring的文檔,實際上是相當簡單的。只要實現自己的NamespaceHandler,再配置一下spring.handlers和spring.schemas就可以了。
http://docs.spring.io/spring/docs/current/spring-framework-reference/html/extensible-xml.html
http://iswift.iteye.com/blog/1657537