天天看点

Spring框架的两个简化XML配置文件的p-namespace和c-namespace

Spring框架的模块化设计,出现了大量的命名空间。应用开发过程中用到的模块,才需要引入对应的命名空间。

Spring框架的丰富功能,导致了Spring框架的XML配置文件十分复杂。这里要介绍的是两个特殊的命名空间,其出现只是为了简化XML配置文件的编写,并未提供应用所需的逻辑功能。

1. p-namespace

在XML配置文件中,首先引入如下命名空间:

xmlns:p="http://www.springframework.org/schema/p"

然后,在对应的<bean>中,使用p:属性(具体名称可定制),而非子元素<property>,以配置其所依赖的其他Spring Bean

示例如下:

<bean name="my_classicBean" class="com.example.ExampleBean">
    <property name="email" value="[email protected]"/>
</bean>
           

   等价于:

<bean name="my_p-namespaceBean" class="com.example.ExampleBean" p:email="[email protected]"/>
           

注意对比上述示例,特别是p:email属性的用法。

2. c-namespace(Spring 3.1及以后出现)

在XML配置文件中,首先引入如下命名空间:

xmlns:c="http://www.springframework.org/schema/c"

然后,在对应的<bean>中,以<bean>的c:属性(具体名称可定制),而非子元素<constructor-arg>,配置其所依赖的其他Spring Bean

示例如下:

<bean id="bar" class="x.y.Bar"/>
<bean id="baz" class="x.y.Baz"/>
<bean id="foo" class="x.y.Foo">
    <constructor-arg ref="bar"/>
    <constructor-arg ref="baz"/>
    <constructor-arg value="[email protected]"/>
</bean>
           

   等价于:

<bean id="bar" class="x.y.Bar"/>
<bean id="baz" class="x.y.Baz"/>
<bean id="foo" class="x.y.Foo" c:bar-ref="bar" c:baz-ref="baz" c:email="[email protected]"/>
           

注意对比上述示例,特别是c:bar-ref, c:baz-ref和c:emial属性的用法。