pring 中 通过 CustomeEditorConfigureer 实现类型转换的一点疑问!
在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; }}
package com.demo11;public class Company { private Person director; public Person getDirector() { return director; } public void setDirector(Person director) { this.director = director; }}
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" name="code">ApplicationContext act = new ClassPathXmlApplicationContext("com/demo11/bean.xml");Company company = (Company)act.getBean("company");System.out.println(company.getDirector().getName());