自定义属性编辑器必须继承 PropertyEditorSupport 类,实现其中的setAsText()方法,将字面值转换为属性类型的对象,再调用setValue()方法,设置转置后的属性对象。
public class CustomCarEditor extends PropertyEditorSupport{
@Override
public void setAsText(String text) throws IllegalArgumentException {
System.out.println("调用setAsText()方法");
if(text==null || text.indexOf(",")==-1){
throw new IllegalArgumentException();
}
String[] infos = text.split(",");
Car car = new Car();
car.setBrand(infos[0]);
car.setMaxSpeed(Integer.parseInt(infos[1]));
car.setPrice(Double.parseDouble(infos[2]));
//调用父类的setValue方法设置转换后的属性对象
setValue(car);
}
}
<!-- 配置属性编辑器 -->
<bean class="org.springframework.beans.factory.config.CustomEditorConfigurer">
<property name="customEditors">
<map>
<!-- 定义一个属性编辑器 -->
<entry>
<!-- 属性编辑器对应的属性类型 -->
<key><value>com.Spring.PropertyEditor.Car</value> </key>
<!-- 对应的属性编辑器Bean -->
<bean class="com.Spring.PropertyEditor.CustomCarEditor"></bean>
</entry>
</map>
</property>
</bean>
<bean id="boss" class="com.Spring.PropertyEditor.Boss">
<property name="name" value="John"></property>
<!-- 使用上面的属性编辑器完成属性填充操作 -->
<property name="car" value="宝马,200,200000"></property>
</bean>
</beans>
public class PropertyEditor {
public static void main(String[] args) {
ApplicationContext cxt = new ClassPathXmlApplicationContext ("com/Spring/PropertyEditor/bean.xml");
Boss boss = (Boss)cxt.getBean("boss");
boss.say();
}
}
CustomEditorConfigurer是实现了BeanFactoryPostProcessor接口的类,因此是一个Bean工厂后处理器,所以在容器启动后有机会注入自定义的属性编辑器。
自定义属性编辑器不常用,一般可以通过引用即<ref>其他的Bean即可,但是有时候比较复杂的情况下,会需要将属性对象一步步肢解为最终可用基本类型表示的Bean,反而会很糟糕,这时可以使用自定义属性编辑器,在setAsText()方法中将字面值转化为属性类型对象。