什么是Spring的命名空間及使用Spring 的命名空間p 裝配屬性


這個就要從XML說了,Spring的配置管理可以利用XML方式進行配置,而XML里面就有命名空間這個概念。。實際上就和標簽的意思有點像 你給一個命名空間以后,這個XML文件里面就可以用那個命名空間上下文里面的標簽了。簡化配置用,你可以去看看Spring AOP用命名空間和不用命名空間的配置有什么區別。

使用Spring 的命名空間p 裝配屬性

使用<property> 元素為Bean 的屬性裝配值和引用並不太復雜。盡管如此,Spring 的命名空間p 提供了另一種Bean 屬性的裝配方式,該方式不需要配置如此多的尖括號。

命名空間p 的schema URI 為http://www.springframework.org/schema/p。如果你想使用命名空間p,只需要在Spring 的XML 配置中增加如下一段聲明:

 
 
 
         
  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <beans xmlns="http://www.springframework.org/schema/beans"
  3. xmlns:p="http://www.springframework.org/schema/p"
  4. xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  5. xsi:schemaLocation="http://www.springframework.org/schema/beans 
  6. http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">

通過此聲明,我們現在可以使用p: 作為<bean> 元素所有屬性的前綴來裝配Bean 的屬性。為了示范,我們重新聲明了kenny Bean 的配置:

 
 
 
         
  1. <bean id="kenny" class="com.springinaction.springidol.Instrumentalist"
  2. p:song = "Jingle Bells"
  3. p:instrument-ref = "saxophone" />

p:song 屬性的值被設置為“Jingle Bells”,將使用該值裝配song 屬性。同樣,p:instrument-ref 屬性的值被設置為“saxophone”,將使用一個ID 為saxophone 的Bean 引用來裝配instrument 屬性。-ref 后綴作為一個標識來告知Spring 應該裝配一個引用而不是字面值。

選擇<property> 還是命名空間p 取決於你,它們是等價的。命名空間p 的最主要優點是更簡潔。在固定寬度的紙張上編寫樣例時,選擇命名空間相對更合適。因此,在本書中你可能看到我不時的使用命名空間p,特別是水平頁面空間比較緊湊時。

 

Spring 的配置文件中,有一個配置文件頭:

<beans xmlns=”http://www.springframework.org/schema/beans”
xsi:schemaLocation=”

http://www.springframework.org/schema/beans

http://www.springframework.org/schema/beans/spring-beans-3.0.xsd”>

這表明,在當前配置文件中,使用的是beans命名空間,可以直接使用<bean id=”">。

如果要在這個配置文件中使用mvc命名空間下的annotation-driven元素,要寫為<mvc:annotation-driven/>,當然,還需要告訴xml解析器,mvc這個命名空間是在哪里定義的,以便解析器能夠驗證當前文件中mvc:開頭的元素是否符合mvc命名空間的:

復制代碼

<beans xmlns=”http://www.springframework.org/schema/beans”
xmlns:mvc=”http://www.springframework.org/schema/mvc”
xsi:schemaLocation=”

http://www.springframework.org/schema/beans

http://www.springframework.org/schema/beans/spring-beans-3.0.xsd

http://www.springframework.org/schema/mvc

http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd”>

復制代碼

這樣解析器在解釋mvc:命名空間的時候,會參考spring-mvc-3.0.xsd這個文件來檢驗<mvc:annotation-driven/>是否合格。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM