* 自定义属性编辑器,spring配置文件中的字符串转换成相应的对象进行注入 spring已经有内置的属性编辑器,我们可以根据需求自己定义属性编辑器 * 如何定义属性编辑器?
1、继承PropertyEditorSupport类,覆写setAsText()方法
2、将属性编辑器注册到spring中
看下面示例:
(1)继承PropertyEditorSupport类,覆写setAsText()方法
import java.beans.PropertyEditorSupport; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Date; /** * 自定义属性编辑器 * @author Administrator */ public class PropertyEditorConvertor extends PropertyEditorSupport { String format = "";//注入到spring中 @Override public void setAsText(String text) throws IllegalArgumentException { SimpleDateFormat sdf = new SimpleDateFormat(format); try { Date date = sdf.parse(text); this.setValue(date); } catch (ParseException e) { e.printStackTrace(); } } public void setFormat(String format) { this.format = format; } }
(2)写一个javaBean,就两属性,这里以转换Date类型为例
public class Bean1 { private String name; private Date date; public String getName() { return name; } public void setName(String name) { this.name = name; } public Date getDate() { return date; } public void setDate(Date date) { this.date = date; } }
(3)配置文件appliactionContext.xml
<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd"> <!-- 属性编辑器 <bean id="propertyEditorConvertor" class="com.bjsxt.spring.PropertyEditorConvertor"></bean> --> <bean id="customEditorConfigurer" class="org.springframework.beans.factory.config.CustomEditorConfigurer"> <property name="customEditors"><!-- 这个name是写死的,是CustomEditorConfigurer类中的属性--> <map><!--spring是将属性放到map里面来实现的转换的 --> <entry key="java.util.Date"><!-- 属性为Date类型的数据 --> <bean class="com.bjsxt.spring.PropertyEditorConvertor"> <!-- 用于转换属性的转换器 --> <property name="format" value="yyyy/MM/dd"/> </bean> </entry> </map> </property> </bean> </beans>
(4)写一个测试
import org.springframework.beans.factory.BeanFactory; import org.springframework.context.support.ClassPathXmlApplicationContext; public class SpringTest { public static void main(String[] args){ BeanFactory factory = new ClassPathXmlApplicationContext("applicationContext.xml"); Bean1 bean1 = (Bean1)factory.getBean("bean1"); System.out.println("bean1.name = " + bean1.getName()); System.out.println("bean1.date = " + bean1.getDate()); } }
OK!如果时间能打印出来,就说明属性编辑器配置好了