6.6 Spring3 欄位格式化,6.6spring3

來源:互聯網
上載者:User

6.6 Spring3 欄位格式化,6.6spring3
6.6Spring3 欄位格式化

正如在前面的小節中說的那樣,core.convert是一個通用的類型轉換系統。它提供了一個統一的ConversionServiceAPI和一個強型別的Converter SPI來實作類別型轉換邏輯。Spring容器使用這個系統來綁定bean的屬性值。另外,SpEL和DataBinder也都利用這個系統來綁定欄位值。比如,當SpEL需要將一個Short強轉成Long來完成expression.setValue(Objectbean, Object value)的操作時,將會由core.convert系統來執行這次強轉。

現在來考慮一個典型的客戶環境(比如一個web或是案頭應用)的類型轉換需求。在這樣的環境中,你需要將String轉換成其他類型來支援客戶回傳過程(譯者註:也就是使用者傳值給伺服器的過程),另外你也需要將它再轉成String來支援頁面渲染過程(譯者註:也就是伺服器將值傳給使用者的過程)。另外,通常你需要將String值本地化。更為通用的core.convert的Converter SPI並不直接支援這樣的格式化需求。所以為了直接支援它,Spring3提出了一個方便的FormatterSPI,它作為PropertyEditors的替代,為客戶環境提供了一個簡單而健壯的實現。

總的來說,當你需要實現通用的類型轉換邏輯時使用Converter SPI,比如java.utils.Date和java.lang.Long類型之間互相轉換時。而當你處於用戶端環境時,比如在web應用中,需要將欄位值解析並以本地化格式輸出時使用FormatterSPI。ConversionService為兩種SPI提供了一個統一的類型轉換API。


FormatterSPI

實現了欄位格式化邏輯的Formatter SPI簡單且是強型別的:

package org.springframework.format;public interface Formatter<T> extends Printer<T>, Parser<T> {}

Formatter繼承了Printer和Parser介面這兩個building-block(組成部分,很有意思的單詞)

public interface Printer<T> {String print(T object, Locale locale);}

import java.text.ParseException;public interface Parser<T> {T parse(String clientValue, Locale locale) throws ParseException;}

想要建立你自己的Formatter,只要實現Formatter介面即可。參數T是需要格式化的物件類型,比如java.util.Date。實現print()方法用來在客戶本地列印出一個格式化且本地化了的T的執行個體。實現parse()方法來將一個用戶端的格式化資料轉化成一個T的執行個體。如果一個解析操作失敗了,那麼你的Formatter應該拋出一個ParseException或是IllegalArgumentException。確保你的Formatter實現是安全執行緒的。

為了方便起見,format子包中已經提供了一些Formatter的實現。number包提供了一個NumberFormatter,CurrencyFormatter和PercentFormatter,它們使用java.text.NumberFormat來格式化java.lang.Number對象。datetime包提供了一個DateFormatter,它使用java.text.DateFormat來格式化java.util.Date對象。datetime.joda包提供了一個基於Joda Time庫的全面的datetime格式化的支援。

考慮一個Formatter實作類別的例子——DateFormatter 

package org.springframework.format.datetime;public final class DateFormatter implements Formatter<Date> {private String pattern;public DateFormatter(String pattern) {this.pattern = pattern;}public String print(Date date, Locale locale) {if(date == null) {return "";}return getDateFormat(locale).format(date);}public Date parse(String formatted, Locale locale) throws ParseException {if(formatted.length() == 0) {return null;}return getDateFormat(locale).parse(formatted);}protected DateFormat getDateFormat(Locale locale) {DateFormat dateFormat = new SimpleDateFormat(this.pattern, locale);dateFormat.setLenient(false);return dateFormat;}}

Spring團隊歡迎來自社區的對於Formatter的貢獻。可以通過http://jira.springframework.org來投稿。


註解驅動的格式化

一會你將會看到的,欄位格式化可以通過欄位類型或註解配置。為了綁定一個註解和一個格式化,實現AnnotationFormatterFactory(譯者註:將A和這個由A而使這個Factory產生的Printer和Parser關聯起來):

package org.springframework.format;public interface AnnotationFormatterFactory<A extends Annotation> {Set<Class<?>> getFieldTypes();Printer<?> getPrinter(A annotation, Class<?> fieldType);Parser<?> getParser(A annotation, Class<?> fieldType);}

參數A是要關聯格式化邏輯的欄位的註解類型,比如org.springframework.format.annotation.DateTimeFormat。getFieldTypes()方法來返回可能會被使用註解的欄位類型。getPrinter()方法用來返回一個Printer來輸出被註解的欄位的值。而getParser()方法用來返回一個Parser來將一個被註解的欄位解析成用戶端要顯示的值。

下面的AnnotationFormatterFactory將@NumberFormat註解綁定到了一個formatter。這個註解允許定義一個數字風格(style,譯者註:比如CURRENCY、PERCENT)或是一個數字格式(pattern,譯者註:比如#,###):

public final class NumberFormatAnnotationFormatterFactory implementsAnnotationFormatterFactory<NumberFormat> {public Set<Class<?>> getFieldTypes() {return new HashSet<Class<?>>(asList(newClass<?>[] {Short.class, Integer.class, Long.class, Float.class,Double.class, BigDecimal.class, BigInteger.class}));}public Printer<Number> getPrinter(NumberFormat annotation,Class<?> fieldType) {return configureFormatterFrom(annotation, fieldType);}public Parser<Number> getParser(NumberFormat annotation,Class<?> fieldType) {return configureFormatterFrom(annotation, fieldType);}private Formatter<Number> configureFormatterFrom(NumberFormat annotation, Class<?> fieldType) {if (!annotation.pattern().isEmpty()) {return new NumberFormatter(annotation.pattern());} else {Style style = annotation.style();if (style == Style.PERCENT) {return new PercentFormatter();} else if (style == Style.CURRENCY) {return new CurrencyFormatter();} else {return new NumberFormatter();}}}}

為了觸發格式化,只需要在欄位上添加@NumberFormat註解即可:

public class MyModel {@NumberFormat(style=Style.CURRENCY)private BigDecimal decimal;}

格式化註解API

org.springframework.format.annocation包中包含了一個便捷的格式化註解API。使用@NumberFormat來格式化java.lang.Number欄位。使用@DateTimeFormat來格式化java.util.Date,java.util.Calendar,java.util.Long或Joda Time欄位。

下面的例子使用@DateTimeFormat將java.util.Date格式化為ISO日期類型(yyyy-MM-dd):

public class MyModel {@DateTimeFormat(iso=ISO.DATE)private Date date;}

FormatterRegistry SPI

FormatterRegistry是一個註冊formatters和converters的SPI。FormattingConversionService是FormatterRegistry的一個實作類別,並且適用於大多數環境。這個實作類別可以使用FormattingConversionServiceFactoryBean來編程式或聲明式的配置成為一個Spring的Bean。由於這個實現也實現了ConversionService,所以它可以直接配置並和Spring的DataBinder和SpEL一起使用。

下面看一下FormatterRegistry SPI:

package org.springframework.format;public interface FormatterRegistry extends ConverterRegistry {void addFormatterForFieldType(Class<?> fieldType, Printer<?> printer, Parser<?> parser);void addFormatterForFieldType(Class<?> fieldType, Formatter<?> formatter);void addFormatterForFieldType(Formatter<?> formatter);void addFormatterForAnnotation(AnnotationFormatterFactory<?, ?> factory);}

正如上面所示,Formatters可以通過欄位類型或者註解來註冊。

FormatterRegistry SPI允許你集中配置格式化規則,而不是在各個Controller中重複這樣的配置。比如,你可能想要將所有的Date欄位都用一定的方式來格式化,或者是具有某一註解的欄位都也用一定的方式來格式化。通過一個共用的FormatterRegistry,一旦你定義了規則,那麼它們將隨時都可以應用到格式化中。


FormatterRegistrar SPI

FormatterRegistrar是一個SPI,它用來通過FormatterRegistry來註冊formatters和converters。

package org.springframework.format;public interface FormatterRegistrar {void registerFormatters(FormatterRegistry registry);}

當需要為指定的格式化類別註冊多個相關的converters和fomatters,比如Date類型的格式化時,FormatterRegistrar非常有用。


在Spring MVC中配置Formatting

在Spring MVC應用中,你可以精確地配置一個自訂的ConversionService執行個體並將它作為一個MVC命名空間中annotation-driven元素的屬性。這個ConversionService可以在Controller的資料繫結時任何需要類型轉換的地方使用。如果沒有精確地配置ConversionService,那麼SpringMVC將會自動註冊一個預設的formatters和converters,可以轉換一些常見的類型,比如說numbers和dates(譯者註:這裡也是需要配置上<mvc:annotation-driven>的)。

為了依賴預設的格式化規則,在你的Spring MVC配置XML檔案中不要加上額外的配置。

<?xml version="1.0" encoding="UTF-8"?><beans xmlns="http://www.springframework.org/schema/beans"xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xsi:schemaLocation="http://www.springframework.org/schema/beanshttp://www.springframework.org/schema/beans/spring-beans-3.0.xsdhttp://www.springframework.org/schema/mvchttp://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd"><mvc:annotation-driven /></beans>

通過這麼一行的配置,為Numbers和Date類型格式化的預設formatters就被註冊好了。包括對@NumberFormat和@DateTimeFormat註解的支援。如果classpath下有Joda Time的jar包的話,那麼還能提供對Joda Time格式化庫的支援。

為了注入一個包含自訂formatters和converters的ConversionSerivce執行個體,我們需要設定conversion-service屬性(mvc命名空間的annotation-driven中),然後在conversionService執行個體中指定自訂的converters,formatters或者FormatterRegistrars作為FormattingConversionServiceFactoryBean的屬性:

<?xml version="1.0" encoding="UTF-8"?><beans xmlns="http://www.springframework.org/schema/beans"xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xsi:schemaLocation="http://www.springframework.org/schema/beanshttp://www.springframework.org/schema/beans/spring-beans-3.0.xsdhttp://www.springframework.org/schema/mvchttp://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd"><mvc:annotation-driven conversion-service="conversionService" /><bean id="conversionService"class="org.springframework.format.support.FormattingConversionServiceFactoryBean"><property name="converters"><set><bean class="org.example.MyConverter" /></set></property><property name="formatters"><set><bean class="org.example.MyFormatter" /><bean class="org.example.MyAnnotationFormatterFactory" /></set></property><property name="formatterRegistrars"><set><bean class="org.example.MyFormatterRegistrar" /></set></property></bean></beans>

注意:當你要使用FormatterRegistrars時,可以閱讀“FormatterRegistrarSPI”這一節得到

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.