Type Conversion
在默认情况下,也会安装各种数字和日期类型的格式化程序,以及通过字段中的 @NumberFormat
和 @DateTimeFormat
自定义的支持。
By default, formatters for various number and date types are installed, along with support
for customization via @NumberFormat
and @DateTimeFormat
on fields.
要注册自定义格式化程序和转换器,请使用以下内容:
To register custom formatters and converters, use the following:
-
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 会在分析和格式化日期值时考虑请求区域设置。这适用于日期表示为含有“输入”窗体字段的字符串的窗体。但是,对于“日期”和“时间”窗体字段,浏览器会使用 HTML 规格中定义的固定格式。对于此类情况,可以如下自定义日期和时间格式化:
By default Spring MVC considers the request Locale when parsing and formatting date values. This works for forms where dates are represented as Strings with "input" form fields. For "date" and "time" form fields, however, browsers use a fixed format defined in the HTML spec. For such cases date and time formatting can be customized as follows:
-
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 实现的更多信息,请参阅 the |
See the |