更简洁的注入方式(P命名空间、C命名空间和复合属性名)

更简洁的注入方式(P命名空间、C命名空间和复合属性名)

p命名空间(p-namespace)

p命名空间:使用<bean/>标签的属性来代替子标签<property/>完成依赖注入。

使用p命名空间,首先要引入p命名空间的XSD(XML Scheema Definition)

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

<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
        https://www.springframework.org/schema/beans/spring-beans.xsd">

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

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

使用p命名空间引用其他bean

<bean name="john-modern"
    class="com.example.Person"
    p:name="John Doe"
    p:spouse-ref="jane"/>

等价于

<bean name="john-classic" class="com.example.Person">
    <property name="name" value="John Doe"/>
    <property name="spouse" ref="jane"/>
</bean>

p:property's name-ref = "xxx"

p:spouse-ref="jane"表示:p表示这里使用p命名空间,spouse是这个bean的一个属性的名字,-ref表示这个属性使用引用其他bean的方式注入

c命名空间(c-namespace)

c命名空间:使用<bean/>标签的属性来代替子标签<constructor-arg/>完成依赖注入。

与p命名空间类似,还是要引入c命名空间的XSD:

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

    <bean id="beanOne" class="x.y.ThingOne" 
        c:thingTwo-ref="beanTwo"  
        c:thingThree-ref="beanThree" 
        c:email="[email protected]"/>

等价于:

   <bean id="beanOne" class="x.y.ThingOne">
        <constructor-arg name="thingTwo" ref="beanTwo"/>
        <constructor-arg name="thingThree" ref="beanThree"/>
        <constructor-arg name="email" value="[email protected]"/>
    </bean>

除了使用name指定构造器的参数外,还可以使用index指定

<bean id="beanOne" class="x.y.ThingOne" 
    c:_0-ref="beanTwo" 
    c:_1-ref="beanThree"
    c:_2="[email protected]"/>

等价于:

<bean id="beanOne" class="x.y.TingOne">
    <constructor-arg index="0" ref="beanTwo"/>
    <constructor-arg index="1" ref="beanThree"/>
    <constructor-arg index="2" value="[email protected]"/>
</bean>

对于c命名空间,官方给出的建议:

In practice, the constructor resolution mechanism is quite efficient in matching arguments, so unless you really need to, we recommend using the name notation through-out your configuration.

构造器解析机制在匹配参数是非常有效,所以,除非确实需要,否则应该自始至终使用name来进行配置。

符合属性名(Compound Property Names)

举个例子进行说明:

<bean id="something" class="things.ThingOne">
    <property name="fred.bob.sammy" value="123" />
</bean>

fred.bob.sammy就是一个符合属性名,表示:id为something的bean,有一个属性为fred,fred有一个属性bob,bob有一个属性sammy。这个setter注入,就是要将sammy的值设为“123”(具体类型从这里还看不出来)

为了完成上述的setter注入,something的fred属性不能是null;fred的bob属性不能是null

发布了213 篇原创文章 · 获赞 116 · 访问量 8万+

猜你喜欢

转载自blog.csdn.net/qq2071114140/article/details/104213684
今日推荐