此外我們還可以使用註解數據格式化來實現數據類型轉換。
例,在vo類的變量聲明上添加@DateTimeFormat(pattern="yyyy-MM-dd")
@DateTimeFormat(pattern="yyyy-MM-dd")
private Date birth;
然後在Spring 的xml文件中配置
<mvc:annotation-driven></mvc:annotation-driven>
可得到與上述設置轉換器方法一樣的效果。
此外還有@NumberFormat(pattern="#,###,###.")數字格式化。
注意數據類型轉換器,與上篇博文中的數據格式化不能同時使用。
若需要同時使用例如:對birth使用數據類型轉換器,而對money使用數據格式化。
private Date birth;
@NumberFormat(pattern="#,###,###.")
private int money;
這時我們就會報格式錯誤的異常,如下。
Field error in object 'userInfo' on field 'mobile': rejected value []; codes [typeMismatch.userInfo.mobile,typeMismatch.mobile,typeMismatch.int,typeMismatch]; arguments [org.springframework.context.support.DefaultMessageSourceResolvable: codes [userInfo.mobile,mobile]; arguments []; default message [mobile]]; default message [Failed to convert property value of type 'java.lang.String' to required type 'int' for property 'mobile'; nested exception is java.lang.NumberFormatException: For input string: ""]
產生這種情況的原因是使用自定義類型轉換器時需要通過ConversionServiceFactoryBean的converters屬性註冊該類型轉換器,此時<mvc:annotation-driven/> 默認創建的ConversionService實例不再擁有DefaultFormattingConversionService對象,而是DefaultConversionService對象,無法使用@DateTimeFormat和@NumberFormat註解
這時我們只需要在Spring配置文件中更改 bean 配置的類爲FormattingConversionServiceFactoryBean 即可同時使用數據類型轉換器和數據格式化。
<bean id="conversionServiceFactoryBean" class="org.springframework.format.support.FormattingConversionServiceFactoryBean">
<property name="converters">
<set>
<ref bean="dateConverter"/>
</set>
</property>
</bean>
嘗試輸入
輸出