Spring P命名空间 02

P命名空间 装配属性

使用<property> 元素为Bean 的属性装配值和引用并不太复杂。尽管如此,Spring 的命名空间p 提供了另一种Bean 属性的装配方式,该方式不需要配置如此多的尖括号。

命名空间p 的schema URI 为http://www.springframework.org/schema/p。如果你想使用命名空间p,只需要在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:p="http://www.springframework.org/schema/p"
xmlns:c="http://www.springframework.org/schema/c"
xsi:schemaLocation="
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd">

 <bean id="grade" class="cn.bean.Grade">
    <property name="name" value="kitty"></property>
</bean>
    <bean id="student" class="cn.bean.Student" p:age="1111" p:name="kikkkk" p:grade-ref="grade">
    </bean>

通过此声明,我们现在可以使用p: 作为<bean> 元素所有属性的前缀来装配Bean 的属性。为了示范,我们重新声明了grade  Bean 的配置:



p:age 属性的值被设置为“11111”,将使用该值装配age属性。同样,p:grade-ref 属性的值被设置为“grade”,将使用一个ID 为grade的Bean 引用来装配Grade属性。-ref 后缀作为一个标识来告知Spring 应该装配一个引用而不是字面值。


选择<property> 还是命名空间p 取决于你,它们是等价的。命名空间p 的最主要优点是更简洁。在固定宽度的纸张上编写样例时,选择命名空间相对更合适。因此,在本书中你可能看到我不时的使用命名空间p,特别是水平页面空间比较紧凑时。




原文地址:https://www.cnblogs.com/cuixiaomeng/p/7677039.html