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:

@Configuration
public class WebConfiguration implements WebMvcConfigurer {

	@Override
	public void addFormatters(FormatterRegistry registry) {
		// ...
	}
}

默认情况下,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:

@Configuration
public class DateTimeWebConfiguration implements WebMvcConfigurer {

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

有关何时使用 FormatterRegistrar 实现的更多信息,请参阅 the FormatterRegistrar SPIFormattingConversionServiceFactoryBean

See the FormatterRegistrar SPI and the FormattingConversionServiceFactoryBean for more information on when to use FormatterRegistrar implementations.