<bean id="my" class="bean.MyClass" scope="prototype">
<constructor-arg>
<value>my value1</value>
</constructor-arg>
<property name="name">
<value>皮球</value>
</property>
<property name="myList">
<list>
<value>value1</value>
<value>value2</value>
</list>
</property>
</bean>
但对于复杂类型的属性或参数,如一个属性的类型是另外一个Java Class,这样就必须在配置文件中再声明这个Java Class,如果这种情况很多时,或是我们做的类要release时,就会给开发人员增加很多工作量。让我们先来举个例子。假设有两个类:Contact和PhoneNumber,Contact的phoneNumber属性的类型是PhoneNumber,代码如下:
public class Contact
{
private PhoneNumber phoneNumber;
public PhoneNumber getPhoneNumber()
{
return phoneNumber;
}
public void setPhoneNumber(PhoneNumber phoneNumber)
{
this.phoneNumber = phoneNumber;
}
}
PhoneNumber类
public class PhoneNumber
{
private String number;
public PhoneNumber(String s)
{
this.number = s;
}
public String getNumber()
{
return number;
}
}
如果直接在XML配置文件中装配Contact类,就需要先装配PhoneNumber类,代码如下:
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.0.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-2.0.xsd">
<bean id="contact" class="bean.Contact">
<property name="phoneNumber">
<ref bean="phoneNumber"/>
</property>
</bean>
<bean id="phoneNumber" class="bean.PhoneNumber">
<constructor-arg>
<value>12345678</value>
</constructor-arg>
</bean>
</beans>
public class PhoneEditor extends java.beans.PropertyEditorSupport
{
@Override
public void setAsText(String text) throws IllegalArgumentException
{
setValue(new bean.PhoneNumber(text));
}
}
这个类的代码非常简单,在setAsText方法中只有一行代码,实际上只是建立一个PhoneNumber对象实例,并将text属性值作为参数值传入PhoneNumber的构造方法。接下来我们在配置文件中安装这个属性编辑器(实际上是装配org.springframework.beans.factory.config.CustomEditorConfigurer类),代码如下:
class="org.springframework.beans.factory.config.CustomEditorConfigurer">
<property name="customEditors">
<map>
<entry key="bean.PhoneNumber">
<bean id="phoneEditor" class="editor.PhoneEditor"/>
</entry>
</map>
</property>
</bean>
从上面的代码可以看出,属性编辑器是使用了CustomEditorConfigurer的customEditors属性进行安装的。这是一个Map类型的属性。key的值必须是属性编辑器最终转换后的类型名,如在本例中,要将文本的参数值转换成bean.PhoneNumber类型的值,因此,key必须为bean.PhoneNumber。 下面我们来使用PhoneEditor属性编辑器类来装配Contact类,代码如下:
<property name="phoneNumber">
<value>87654321</value>
</property>
</bean>
import org.springframework.context.*;
import org.springframework.context.support.*;
public class Test
{
public static void main(String[] args)
{
// 上面的配置代码都在applicationContext.xml文件中
ApplicationContext context = new FileSystemXmlApplicationContext("src\\applicationContext.xml");
bean.Contact contact = (bean.Contact) context.getBean("contact");
System.out.println(contact.getPhoneNumber().getNumber());
}
}
















