天天看點

Spring自定義屬性轉換器

自定義屬性轉換器

  • 首先建立一個類繼承PropertyEditorSupport
  • 然後重新setAsText(String text);方法
  • 最後在Spring配置檔案中配置該類的引用

·示例代碼·

/**
*自定義一個時間轉換器
*/
public class UtilDatePropertyEditor extends PropertyEditorSupport{

    //定義時間格式的字元串
    private String formatContext;

    @override
    public 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>