<bean id= "cdPlay" class = "soundsystem.CDPlay">
<property name="compactDisc" red="compactDisc" />
</bean>
<property>元素是爲屬性的Setter方法所提供的功能,Spring提供了簡潔的p命名空間來替代<property>元素。
爲啓用p命名空間,需要在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:p="http://www.springframework.org/schema/p"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.0.xsd>
...
</beans>
<bean id = "cdPlayer" class="soundsystem.CDPlay"
p:compactDisc-ref = "compactDisc" />
p-命名空間中屬性所遵循的命名規則和c-命名空間屬性類型:
p:屬性名-ref ="所注入的beanId" //-ref:注入bean引用,告訴spring這裏裝配的是引用,而不是字面量值
將字面量注入到屬性中
<bean id = "cdPlayer" class="soundsystem.CDPlay" >
<property name = "title" value = "this is title name value">
</bean>
p命名空間
<bean id = "cdPlayer" class="soundsystem.CDPlay"
p:title = "this is title name value"
p:artist = "this is artist value">
<property name ="屬性名">
<list>
<value>this first value </value>
<value>this second value</value>
</list>
<property>
</bean>
與c命名空間一樣,裝配bean引用與裝配字面量的唯一區別在於是否帶有"-ref"後綴,如果沒有"-ref"後綴,所裝配的就是字面量。
雖然不能使用p-命名空間來裝配集合,但是可以使用Spring util-命名空間中的一些功能來簡化。
首先,在XML中聲明util-命名空間及其模式
<?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:p="http://www.springframework.org/schema/p"
xmlns:util="http://www.springframework.org/schema/util"
xsi:schemaLocation="http://www.springframework.org/schema/util
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.0.xsd>
...
</beans>
util-命名空間所提供的功能之一就是<util:list>元素,它會創建一個列表的bean:
<util:list id="listId">
<value> this is one value</value>
<value> this is two value</value>
</util:list>
<bean id = "compactDisc" class="soundsystem.BlankDisc"
p:title="this is title name"
p:artist = "this is a vale"
p:tracks-ref="listId" /> //該屬性名爲tracks,依賴上面util:list所創建的list bean .
util-命名空間的其他元素:
<util:constant> 引用某個類型的public static域,並將其暴露爲bean
<util:list> 創建一個java.util.list的bean,其中包含值和引用
<util:map> 創建一個java.util.map類型的bean,其中包含值和引用
<util:properties> 創建一個java.util.properties類型的bean
<util:property-path> 創建一個ben的屬性(或內嵌屬性),並將其暴露
<util:set> 創建一個java.util.Set類型的bean,其中包含值和引用