1. 程式人生 > >Spring的自定義屬性編輯器

Spring的自定義屬性編輯器

什麼是屬性編輯器:自定義屬性編輯器就是將Spring的字串轉換成相對應的物件進行注入,Spring已經有了內建的屬性編輯器,我們可以自己定義屬性編輯器。

如何定義屬性編輯器:

(1)繼承PropertyEditorSupport,重寫setAsText()方法。

package com.bjsxt.spring;

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;

}

}


(2)將屬性編輯器註冊到Spring中。

<bean id="customEditorConfigurer" class="org.springframework.beans.factory.config.CustomEditorConfigurer">

<property name="customEditors">

<map>

<entry key="java.util.Date">

<bean class="com.bjsxt.spring.UtilDatePropertyEditor">

<property name="format" value="yyyy-MM-dd"/>

</bean>

</entry>

</map>

</property>

</bean>