在spring中可以通过CustomeEditorConfigurer自动去检测bean包所需要转换属性,自定义一个继承于 PropertyEditorSupport的 Editor类,通过配置文件注入到 CustomeEditoConfigurer类中,当该属性在容器中的值是字符串时,他就会调用setTextAs(String text),把字符串值转换成目标类型的实例。如果不能正转换,则抛出相应的异常...例子如下
Person.java
package com.demo11;
public class Person {
private String name;
private String sex;
private int age;
public Person(String name, int age, String sex){
this.name = name;
this.age= age;
this.sex = sex;
}
public String getSex(){
return sex;
}
public void setSex(String sex) {
this.sex = sex;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
}
Company.java 其中包含 Person属性.
package com.demo11;
public class Company {
private Person director;
public Person getDirector() {
return director;
}
public void setDirector(Person director) {
this.director = director;
}
}
PersonEditor.java //继承自PropertyEditorSupport
package com.demo11;
import java.beans.PropertyEditorSupport;
public class PersonEditor extends PropertyEditorSupport {
@Override
public void setAsText(String text) throws IllegalArgumentException {
String[] tmp =text.split("-");
String name = tmp[0];
int age = Integer.parseInt(tmp[1]);
String sex = tmp[2];
Person person = new Person(name, age, sex);
setValue(person);
}
}
对应的配置文件:
<bean id="customEditorConfigurer"
class="org.springframework.beans.factory.config.CustomEditorConfigurer">
<property name="customEditors">
<map>
<entry key="com.demo11.Person">
<bean class="com.demo11.PersonEditor"></bean>
</entry>
</map>
</property>
</bean>
<bean id="company" class="com.demo11.Company">
<property name="director">
<value>nono-35-女</value>
</property>
</bean>
在测试类中
ApplicationContext act = new ClassPathXmlApplicationContext("com/demo11/bean.xml");
Company company = (Company)act.getBean("company");
System.out.println(company.getDirector().getName());
输出结果为 nono
这的确是很好的编程思想,但是这在实际应用中有啥好处,或者有哪些实用场合 ?目前为止我还孤陋寡闻,尚不知结果,希望看到的朋友能给我指教指教![size=large][/size]!