javabean:
package Bean.CustomerPropertyEditor;

public class Company ...{
private Person director;

public Person getDirector() ...{
return director;
}

public void setDirector(Person director) ...{
this.director = director;
}
}

package Bean.CustomerPropertyEditor;

public class Person ...{
private String name;
private int age;
public Person(String name,int age)...{
this.name=name;
this.age=age;
}
public int getAge() ...{
return age;
}
public void setAge(int age) ...{
this.age = age;
}
public String getName() ...{
return name;
}
public void setName(String name) ...{
this.name = name;
}
}
自定义PropertyEditor
package Bean.CustomerPropertyEditor;
import java.beans.PropertyEditorSupport;

public class PersonEditor extends PropertyEditorSupport ...{
@Override
public void setAsText(String text) throws IllegalArgumentException ...{
String[] temp=text.split("-");
String name=temp[0];
int age=Integer.parseInt(temp[1]);
Person p=new Person(name,age);
setValue(p);
}
}
配置文件:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN//EN" "http://www.springframework.org/dtd/spring-beans.dtd">
<beans>
<bean id="customEditorConfigure" class="org.springframework.beans.factory.config.CustomEditorConfigurer">
<property name="customEditors">
<map>
<!-- 确定目标类 -->
<entry key="Bean.CustomerPropertyEditor.Person">
<bean class="Bean.CustomerPropertyEditor.PersonEditor"></bean>
</entry>
</map>
</property>
</bean>
<bean id="company" class="Bean.CustomerPropertyEditor.Company">
<property name="director">
<value>gaoxiang-26</value>
</property>
</bean>
</beans>
测试代码:
package Bean.CustomerPropertyEditor;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.FileSystemXmlApplicationContext;
import Bean.FactoryMethods.Test;

public class test ...{

/** *//**
* @param args
*/
public static void main(String[] args) ...{
String path=new Test().getClass().getResource("/").getPath();
String realpath=path.substring(1, path.length());
ApplicationContext context=new FileSystemXmlApplicationContext(realpath+"/propertyEditor.xml");
Company c=(Company)context.getBean("company");
System.out.println(c.getDirector().getName()+"*"+c.getDirector().getAge());
}
}
运行结果:
gaoxiang*26
1613

被折叠的 条评论
为什么被折叠?



