ITeye博客

spring中自定义属性编辑器CustomEditorConfigurer

gundumw100 · 2010-01-19 09:51 · spring · 企业架构 · Java · junit · Spring · XML · Markdown

什么是属性编辑器,作用? * 自定义属性编辑器,spring配置文件中的字符串转换成相应的对象进行注入 spring已经有内置的属性编辑器,我们可以根据需求自己定义属性编辑器 * 如何定义属性编辑器? * 继承PropertyEditorSupport类,覆写setAsText()方法,参见:UtilDatePropertyEditor.java * 将属性编辑器注册到spring中,参见:applicationContext.xml 比如: 有一个类里面有一个Date属性 [code="java"] public class Bean1 { private Date dateValue; public void setDateValue(Date dateValue) { this.dateValue = dateValue; } } [/code] applicationContext.xml配置文件如下: [code="java"] 2008-08-15 [/code] UtilDatePropertyEditor.java 如下,必须继承java.beans.PropertyEditorSupport类,覆写setAsText()方法 [code="java"] import java.beans.PropertyEditorSupport; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Date; /** * java.util.Date属性编辑器 * @author Administrator * */ public class UtilDatePropertyEditor extends PropertyEditorSupport { private String format="yyyy-MM-dd"; @Override public void setAsText(String text) throws IllegalArgumentException { System.out.println("UtilDatePropertyEditor.saveAsText() -- text=" + text); SimpleDateFormat sdf = new SimpleDateFormat(format); try { Date d = sdf.parse(text); this.setValue(d); } catch (ParseException e) { e.printStackTrace(); } } public void setFormat(String format) { this.format = format; } } [/code] 这样就可以完成正确解析了,注意customEditors是Spring的类CustomEditorConfigurer提供的属性,是一个Map,里面存放的都是自定义的编辑器(customEditors),比如这里存放的是UtilDatePropertyEditor日期编辑器,看CustomEditorConfigurer源码就知道了。 测试一下: [code="java"] import org.springframework.beans.factory.BeanFactory; import org.springframework.context.support.ClassPathXmlApplicationContext; import junit.framework.TestCase; public class InjectionTest extends TestCase { private BeanFactory factory; @Override protected void setUp() throws Exception { factory = new ClassPathXmlApplicationContext("applicationContext.xml"); } public void testInjection1() { Bean1 bean1 = (Bean1)factory.getBean("bean1"); System.out.println("bean1.dateValue=" + bean1.getDateValue()); } } [/code] 能打印出日期就OK了。

评论(1)

  1. #1 楼 · javatozhang · 2014-04-23 17:13

    很清晰、谢谢你的分析!

评论功能维护中,当前仅展示历史评论。