Spring设置属性 && p命名空间 、 util命名空间

<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,其中包含值和引用

猜你喜欢

转载自blog.csdn.net/m0_37668842/article/details/82734301