类型转换
默认情况下,会安装各种数字和日期类型的格式化工具,并支持通过@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 SPI和FormattingConversionServiceFactoryBean。