p命名空间是在Spring2.0中引进的,主要是为了简化配置文件中属性声明的写法,可以直接使用自定义的属性。其中需要注意的一点是,p命名空间没有对应的Schema文件,因为没有办法预先知道用户使用的属性名称,所以也就无法定义Schema文件。
使用p命名空间后,相关的解析由SimplePropertyNamespaceHandler处理。如果属性名以"-ref"后缀结束,表示定义的属性为一个Bean引用,解析时只取后缀之前的字符串作为属性名,并以属性值作为引用来查找对应 的Bean。
例如:
<bean id="rob" class="..TestBean" p:name="Rob Harrop" p:spouse-ref="sally"/>
<bean id="sally" .../>
p:name,表示的是TestBean中定义的name属性(非Spring中的Bean定义属性name)。
p:spouse-ref,表示的TestBean中的spouse属性,其对应的值为配置文件中定义的“sally” Bean。
附:NamespaceHandler
的JavaDoc:
Simple NamespaceHandler
implementation that maps custom attributes directly through to bean properties. An important point to note is that thisNamespaceHandler
does not have a corresponding schema since there is no way to know in advance all possible attribute names.
An example of the usage of this NamespaceHandler
is shown below:
<bean id="rob" class="..TestBean" p:name="Rob Harrop" p:spouse-ref="sally"/>
Here the ' p:name
' corresponds directly to the ' name
' property on class ' TestBean
'. The ' p:spouse-ref
' attributes corresponds to the ' spouse
' property and rather than being the concrete value it conatins the name of the bean that will be injected into that property.