2017/12/24 Spring属性配置细节(下)
集合属性
<!-- 测试如何配置集合属性 -->
<bean id="person3" class="com.spring.helloworld.collection.Person">
<property name="name" value="haha"></property>
<property name="age" value="23"></property>
<property name="cars">
<list>
<!-- 使用List节点来为list类型的属性赋值 -->
<ref bean="car"/>
<ref bean="car2"/>
<bean class="com.spring.helloworld.Car">
<constructor-arg value="Ford"></constructor-arg>
<constructor-arg value="Changan"></constructor-arg>
<constructor-arg value="20000" type="double"></constructor-arg>
</bean>
</list>
</property>
</bean>
<!-- 配置Map属性值 -->
<bean id="newperson" class="com.spring.helloworld.collection.NewPerson">
<property name="name" value="heihei"></property>
<property name="age" value="23"></property>
<property name="cars">
<!-- 使用Map节点以及Map的entry子节点配置Map类型的成员变量 -->
<map>
<entry key="AA" value-ref="car"></entry>
<entry key="BB" value-ref="car2"></entry>
</map>
</property>
</bean>
使用props和prop子节点
<!-- 配置Properties属性值 -->
<bean id="dataSource" class="com.spring.helloworld.collection.DataSource">
<property name="properties">
<!-- 使用props和prop子节点来为Properties属性赋值 -->
<props>
<prop key="user">root</prop>
<prop key="passWord">1234</prop>
<prop key="jdbcUrl">jdbc:mysql:///test</prop>
<prop key="driverClass">com.mysql.jdbc.Driver</prop>
</props>
</property>
</bean>
内部bean是不能被外部引用的,所以我们需要配置独立的集合bean以供多个bean使用,需要导入util命名空间
<!-- 配置独立的集合bean以供多个bean使用 ,需要导入util命名空间-->
<util:list id="cars">
<ref bean="car"/>
<ref bean="car2"/>
</util:list>
<bean id="person4" class="com.spring.helloworld.collection.Person">
<property name="name" value="Jack"></property>
<property name="age" value="23"></property>
<property name="cars" ref="cars"></property>
</bean>
<!-- 通过p命名空间为bean属性赋值,需要先导入p命名空间 ,相对于传统的配置方式更加的简洁-->
<bean id="person5" class="com.spring.helloworld.collection.Person" p:age="30"
p:name="Queen" p:cars-ref="cars"></bean>