spring核心:bean工厂的装配 4

本文中主要包含:

12.使用value元素设定属性

13.使用null设定空值

14.使用collection设定集合

15.定义内部bean

16.使用idref元素预检查错误

17.使用ref设定依赖

18.value和ref的简写


12.使用value元素设定属性

spring中value元素通常使用字符串来制定属性,但是spring在背后会使用javaBeans的PropertiesEditors将这些字符串从java.lang.String转换成真实的类型。

13.使用null设定空值

<value></value>

上面其实相当于一个""字符串,如果想要设置value为null,可以这么写:

<value><null/></value>

14.使用collection设定集合

一个简单demo:

ComplexBean.java :

/** * */ package beanfactory.coredi; import java.util.List; import java.util.Map; import java.util.Properties; import java.util.Set; /** * @author jefferyxu * */ public class ComplexBean { private Properties people; private List someList; private Map someMap; private Set someSet; /** * @return the people */ public Properties getPeople() { return people; } /** * @param people the people to set */ public void setPeople(Properties people) { this.people = people; } /** * @return the someList */ public List getSomeList() { return someList; } /** * @param someList the someList to set */ public void setSomeList(List someList) { this.someList = someList; } /** * @return the someMap */ public Map getSomeMap() { return someMap; } /** * @param someMap the someMap to set */ public void setSomeMap(Map someMap) { this.someMap = someMap; } /** * @return the someSet */ public Set getSomeSet() { return someSet; } /** * @param someSet the someSet to set */ public void setSomeSet(Set someSet) { this.someSet = someSet; } }

选择class,然后通过选择“Add class Properties”得到所有的属性。

spring核心:bean工厂的装配 4

然后通过edit来实现属性的编辑 :

spring核心:bean工厂的装配 4

最终生成applicationContext.xml如下:

<bean id="complexBean" class="beanfactory.coredi.ComplexBean" abstract="false" lazy-init="default" autowire="default"> <property name="someList"> <list> <ref bean="anotherBean" /> <value type="java.lang.String">list中的第一个元素</value> </list> </property> <property name="someMap"> <map> <entry key="key-string" value="我是字符串甲"></entry> </map> </property> <property name="people"> <props> <prop key="author">jefferyxu</prop> <prop key="age">20</prop> </props> </property> <property name="someSet"> <set> <value>我是字符串甲</value> </set> </property> </bean>

可以这么使用:

ComplexBean complexBean = (ComplexBean)context.getBean("complexBean"); String author = complexBean.getPeople().getProperty("author"); System.out.println(author);

15.定义内部bean

内部的bean不需要任何的id或者是singleton,仅仅供外部类使用。

16.使用idref元素预检查错误

使用idref,spring在加载时就检查其他的bean是否存在。idref可以配合local(bean在同一个文件中)或者是bean使用。

17.使用ref设定依赖

ref包含三个属性值:parent,local,bean。

18.value和ref的简写

<constructor-arg index="2"> <value>1</value> </constructor-arg>

可以简写成:

<constructor-arg index="2" value="1"> </constructor-arg>