5.7 配置一个全局的日期&时间格式 {#toc_24}
默认情况下,未被@DateTimeFormat注解的日期和时间字段会使用DateFormat.SHORT风格从字符串转换。如果你愿意,你可以定义你自己的全局格式来改变这种默认行为。
你将需要确保Spring不会注册默认的格式化器,取而代之的是你应该手动注册所有的格式化器。请根据你是否依赖Joda Time库来确定是使用org.springframework.format.datetime.joda.JodaTimeFormatterRegistrar类还是org.springframework.format.datetime.DateFormatterRegistrar类。
例如,下面的Java配置会注册一个全局的’yyyyMMdd’格式,这个例子不依赖于Joda Time库:
@Configurationpublic class AppConfig {@Beanpublic FormattingConversionService conversionService() {// Use the DefaultFormattingConversionService but do not register defaultsDefaultFormattingConversionService conversionService = new DefaultFormattingConversionService(false);// Ensure @NumberFormat is still supportedconversionService.addFormatterForFieldAnnotation(new NumberFormatAnnotationFormatterFactory());// Register date conversion with a specific global formatDateFormatterRegistrar registrar = new DateFormatterRegistrar();registrar.setFormatter(new DateFormatter("yyyyMMdd"));registrar.registerFormatters(conversionService);return conversionService;}}
如果你更喜欢基于XML的配置,你可以使用一个FormattingConversionServiceFactoryBean,这是同一个例子,但这次使用了Joda Time:
<?xml version="1.0" encoding="UTF-8"?><beans xmlns="http://www.springframework.org/schema/beans"xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xsi:schemaLocation="http://www.springframework.org/schema/beanshttp://www.springframework.org/schema/beans/spring-beans.xsd><bean id="conversionService" class="org.springframework.format.support.FormattingConversionServiceFactoryBean"><property name="registerDefaultFormatters" value="false" /><property name="formatters"><set><bean class="org.springframework.format.number.NumberFormatAnnotationFormatterFactory" /></set></property><property name="formatterRegistrars"><set><bean class="org.springframework.format.datetime.joda.JodaTimeFormatterRegistrar"><property name="dateFormatter"><bean class="org.springframework.format.datetime.joda.DateTimeFormatterFactoryBean"><property name="pattern" value="yyyyMMdd"/></bean></property></bean></set></property></bean></beans>
Joda Time提供了不同的类型来表示
date、time和date-time的值,JodaTimeFormatterRegistrar中的dateFormatter、timeFormatter和dateTimeFormatter属性应该为每种类型配置不同的格式。DateTimeFormatterFactoryBean提供了一种方便的方式来创建格式化器。在
如果你在使用Spring MVC,请记住要明确配置所使用的转换服务。针对基于@Configuration的Java配置方式这意味着要继承WebMvcConfigurationSupport并且覆盖mvcConversionService()方法。针对XML的方式,你应该使用mvc:annotation-drive元素的'conversion-service'属性。更多细节请看Section 18.16.3 “Conversion and Formatting”。
