Spring配置文件beans.xml頭部配置解釋

看如下的beans.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"
    xsi:schemaLocation="http://www.springframework.org/schema/beans
                        http://www.springframework.org/schema/beans/spring-beans.xsd">
  
  
</beans>

解釋:

1、【xmlns="http://www.springframework.org/schema/beans"】

聲明xml文件默認的命名空間,表示未使用其他命名空間的所有標籤的默認命名空間。

2、【xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"】

聲明XML Schema實例,聲明後就可以使用schemaLocation屬性。

3、【xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd】

指定Schema的位置這個屬性必須結合命名空間使用。這個屬性有兩個值,第一個值表示需要使用的命名空間。第二個值表示供命名空間使用的XML schema的位置。

上面配置的命名空間指定xsd規範文件,這樣你在進行下面具體配置的時候就會根據這些xsd規範文件給出相應的提示,比如說每個標籤是怎麼寫的,都有些什麼屬性是都可以智能提示的,在啓動服務的時候也會根據xsd規範對配置進行校驗。

配置技巧:對於屬性值的寫法是有規律的,中間使用空格隔開,後面的值是前面的補充,也就是說,前面的值是去除了xsd文件後得來的。

如下所示是一個引入了使用aop和tx功能的beans.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"
    xsi:schemaLocation="
        http://www.springframework.org/schema/beans
        http://www.springframework.org/schema/beans/spring-beans.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>

解釋:

1、【xmlns:aop="http://www.springframework.org/schema/aop"】

聲明前綴爲aop的命名空間,後面的URL用於標示命名空間的地址不會被解析器用於查找信息。其惟一的作用是賦予命名空間一個惟一的名稱。當命名空間被定義在元素的開始標籤中時,所有帶有相同前綴的子元素都會與同一個命名空間相關聯。

同時也是爲beans.xml文件引入aop的功能,引入後就可以在包裹的範圍內使用<aop>標籤。

2、【xmlns:tx="http://www.springframework.org/schema/tx"】

原理同上。

3、xsi:schemaLocation屬性同上解釋,使用快速的方法來定位和編寫這個url。

 

一些技巧:

關於在beans.xml要使用哪些功能,官網上已經提供了每個功能說明和標準的頭文件信息,當我們在開發使用時要哪些功能,都可以上官網去定位。

http://docs.spring.io/spring/docs/current/spring-framework-reference/htmlsingle/#xsd-configuration

其實這個地址的入口在這裏http://projects.spring.io/spring-framework/,打開之後,定位到右邊邊,想要哪個版本點進去即可。

於書寫的技巧,比如一些標籤已經沒有內嵌了,那麼會有兩種寫法,這兩種寫法效果都是一直的,如:<context:annotation-config/>和<context:annotation-config></context:annotation-config>,爲了美觀來說,我們會選擇前者。

 

總結:

XML Schema命名空間避免命名衝突,就像Java中的package一樣,將不同作用的標籤分門別類(比如Spring中的tx命名空間針對事務類的標籤,context命名空間針對組件的標籤)。

 

原文:https://www.cnblogs.com/EasonJim/p/6880329.html

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章