屬性編輯器
什么是屬性編輯器,作用??
?????spring已經(jīng)有內(nèi)置的屬性編輯器,它的作用是 spring配置文件中的字符串轉(zhuǎn)換成相應(yīng)的對(duì)象進(jìn)行注入,
我們可以根據(jù)需求自己定義屬性編輯器
??
什么時(shí)候需要自定義屬性編輯器
? 某些時(shí)候需要自定義,spring內(nèi)置的屬性編輯器,不能把字符串轉(zhuǎn)換成相應(yīng)的對(duì)象。
如注入的日期字符串,不能轉(zhuǎn)換成日期類型注入對(duì)象。就需要自定義屬性編輯器。
如何定義屬性編輯器?
??* 繼承PropertyEditorSupport類,覆寫(xiě)setAsText()方法,參見(jiàn):UtilDatePropertyEditor.java
??* 將屬性編輯器注冊(cè)到spring中,參考如下:
<!--第一種,利用spring的注入把?日期樣式也作為一個(gè)參數(shù),更加靈活-->??
<bean?id="customEditorConfigurer"?class="org.springframework.beans.factory.config.CustomEditorConfigurer">
?2???<property?name="customEditors">
?3????<map>
?4?????<entry?key="java.util.Date">
?5??????<bean?class="com.bjsxt.spring.UtilDatePropertyEditor">
?6???????<property?name="format"?value="yyyy-MM-dd"/>
?7??????</bean>
?8?????</entry>
?9????</map>
10???</property>
11??</bean>?
12??<!--第二種?-->
13??<!--?
14??<bean?id="utilDatePropertyEditor"?class="com.bjsxt.spring.UtilDatePropertyEditor"></bean>
15???-->
<bean?id="customEditorConfigurer"?class="org.springframework.beans.factory.config.CustomEditorConfigurer">
?2???<property?name="customEditors">
?3????<map>
?4?????<entry?key="java.util.Date">
?5??????<bean?class="com.bjsxt.spring.UtilDatePropertyEditor">
?6???????<property?name="format"?value="yyyy-MM-dd"/>
?7??????</bean>
?8?????</entry>
?9????</map>
10???</property>
11??</bean>?
12??<!--第二種?-->
13??<!--?
14??<bean?id="utilDatePropertyEditor"?class="com.bjsxt.spring.UtilDatePropertyEditor"></bean>
15???-->
java部分代碼:
?1?/**
?2??*?java.util.Date屬性編輯器?
?3??*?@author?Administrator
?4??*
?5??*/
?6?public?class?UtilDatePropertyEditor?extends?PropertyEditorSupport?{
?7?
?8??private?String?format="yyyy-MM-dd";
?9??
10??@Override
11??public?void?setAsText(String?text)?throws?IllegalArgumentException?{
12???System.out.println("UtilDatePropertyEditor.saveAsText()?--?text="?+?text);
13???
14???SimpleDateFormat?sdf?=?new?SimpleDateFormat(format);
15???try?{
16????Date?d?=?sdf.parse(text);
17????this.setValue(d);
18???}?catch?(ParseException?e)?{
19????e.printStackTrace();
20???}
21??}
22?
23??public?void?setFormat(String?format)?{
24???this.format?=?format;
25??}
26?
27?}
28?
29?
?2??*?java.util.Date屬性編輯器?
?3??*?@author?Administrator
?4??*
?5??*/
?6?public?class?UtilDatePropertyEditor?extends?PropertyEditorSupport?{
?7?
?8??private?String?format="yyyy-MM-dd";
?9??
10??@Override
11??public?void?setAsText(String?text)?throws?IllegalArgumentException?{
12???System.out.println("UtilDatePropertyEditor.saveAsText()?--?text="?+?text);
13???
14???SimpleDateFormat?sdf?=?new?SimpleDateFormat(format);
15???try?{
16????Date?d?=?sdf.parse(text);
17????this.setValue(d);
18???}?catch?(ParseException?e)?{
19????e.printStackTrace();
20???}
21??}
22?
23??public?void?setFormat(String?format)?{
24???this.format?=?format;
25??}
26?
27?}
28?
29?
posted on 2009-04-12 23:35 luofeng225 閱讀(266) 評(píng)論(0) 編輯 收藏 所屬分類: Spring