當前位置:
首頁 >
前端技术
> javascript
>内容正文
javascript
Spring自定义属性转换器
生活随笔
收集整理的這篇文章主要介紹了
Spring自定义属性转换器
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
自定義屬性轉換器
- 首先新建一個類繼承PropertyEditorSupport
- 然后重新setAsText(String text);方法
- 最后在Spring配置文件中配置該類的引用
·示例代碼·
/** *自定義一個時間轉換器 */ public class UtilDatePropertyEditor extends PropertyEditorSupport{//定義時間格式的字符串private String formatContext;@overridepublic void setAsText(String text) throws IllegalArgumentException{//將傳入的時間字符串按照設置的格式格式化Date date = new SimpleDateFormat(formatContext).parse(text);this.setValue(date);}catch(ParseException e){e.printStackTrace();}}//setter..public String setFormatContext(String formatContext){this.formatContext = formatContext;}}Spring中的配置
<!-- org.springframework.beans.factory.config.CustomEditor 這是一個Spring提供的類,用來自定義屬性轉換器 --> <bean id="customEditor" class="org.springframework.beans.factory.config.CustomEditor" ><!-- customEditors屬性是一個Map類型,用來存儲自定義屬性轉換器 --><property name="customEditors" ><map><!-- Map的key值保存的是數據類型 --><entry key="java.util.Date" ><!-- 將我們自定義的編輯器放入Map的value中 --><!-- 也可以將該類單獨配置在entry中用value-ref引用 --><bean class="com.util.UtilDatePropertyEditor"><!-- 注入需要轉換的格式類型 --><property name="formatContext" value="yyyy-MM-dd" /></bean></entry></map></property> </bean> <!-- 如下某個類 --> <bean id="someClass" class="packageName.SomeClassName"><!-- 某個java.util.Date類型屬性 --><property name="dateValue" value="2099-12-31" /> </bean>總結
以上是生活随笔為你收集整理的Spring自定义属性转换器的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: htc G18 一键解锁,3键root
- 下一篇: javascript animation