spring之使用命名空间p来简化bean的配置

时间:2022-07-23
本文章向大家介绍spring之使用命名空间p来简化bean的配置,主要内容包括其使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。

一般情况下,我们是这么配置bean的:

    <bean id="car1" class="com.gong.spring.beans.Car">
        <property name="name" value="baoma"></property>
    </bean>
    <bean id="car2" class="com.gong.spring.beans.Car">
        <property name="name" value="benchi"></property>
    </bean>
    <bean id="car3" class="com.gong.spring.beans.Car">
        <property name="name" value="binli"></property>
    </bean>
    
    <bean id="student" class="com.gong.spring.beans.Student">
        <property name="name" value="tom"></property>
        <property name="age" value="12"></property>
        <property name="score" value="98.00"></property>
        <property name="cars" ref="cars">
        </property>
        
    </bean>
    
    <util:list id="cars">
        <ref bean="car1"/>
        <ref bean="car2"/>
        <ref bean="car3"/>
    </util:list>

说明:cars是公用的集合Bean,Student里有name、age、score以及类型为List<Car>的car属性。

在引入了命名空间之后,我们就可以这么进行配置了:

    <bean id="car1" class="com.gong.spring.beans.Car" p:name="baoma"></bean>
    <bean id="car2" class="com.gong.spring.beans.Car" p:name="benchi"></bean>
    <bean id="car3" class="com.gong.spring.beans.Car" p:name="binli"></bean>
    
    <bean id="student" class="com.gong.spring.beans.Student"
    p:name="tom" p:age="12" p:score="98.00" p:cars-ref="cars"></bean>
    
    <util:list id="cars">
        <ref bean="car1"/>
        <ref bean="car2"/>
        <ref bean="car3"/>
    </util:list>

相较于原来的,代码简洁了很多。