型別轉換
預設情況下,會安裝各種數字和日期型別的格式化程式,並支援透過在欄位和引數上使用 @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 在解析和格式化日期值時會考慮請求的區域設定。這適用於日期以字串形式表示的“輸入”表單欄位。但是,對於“日期”和“時間”表單欄位,瀏覽器使用 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。 |