类型转换

默认情况下,安装了各种数字和日期类型的格式化器,并支持通过字段和参数上的 @NumberFormat@DurationFormat@DateTimeFormat 进行定制。

要注册自定义格式化器和转换器,请使用以下方法

  • Java

  • Kotlin

  • Xml

@Configuration
public class WebConfiguration implements WebMvcConfigurer {

	@Override
	public void addFormatters(FormatterRegistry registry) {
		// ...
	}
}
@Configuration
class WebConfiguration : WebMvcConfigurer {

	override fun addFormatters(registry: FormatterRegistry) {
		// ...
	}
}
<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>

默认情况下,Spring MVC 在解析和格式化日期值时会考虑请求的 Locale。这适用于日期在表单中以字符串形式使用“input”表单字段表示的情况。然而,对于“date”和“time”表单字段,浏览器使用 HTML 规范中定义的固定格式。对于这些情况,日期和时间格式化可以按如下方式定制

  • Java

  • Kotlin

@Configuration
public class DateTimeWebConfiguration implements WebMvcConfigurer {

	@Override
	public void addFormatters(FormatterRegistry registry) {
		DateTimeFormatterRegistrar registrar = new DateTimeFormatterRegistrar();
		registrar.setUseIsoFormat(true);
		registrar.registerFormatters(registry);
	}
}
@Configuration
class DateTimeWebConfiguration : WebMvcConfigurer {

	override fun addFormatters(registry: FormatterRegistry) {
		DateTimeFormatterRegistrar().apply {
			setUseIsoFormat(true)
			registerFormatters(registry)
		}
	}
}
有关何时使用 FormatterRegistrar 实现的更多信息,请参阅 FormatterRegistrar SPIFormattingConversionServiceFactoryBean