型別轉換
預設情況下,安裝了各種數字和日期型別的格式化器,並支援透過欄位和引數上的 @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 。 |