默认情况下,各种数字和日期类型的格式化器被安装,同时支持通过字段上的 @NumberFormat和 @DateTimeFormat进行自定义。
要在 Java 配置中注册自定义格式器和转换器,请使用以下方法:
@Configuration@EnableWebMvcpublic class WebConfig implements WebMvcConfigurer {@Overridepublic void addFormatters(FormatterRegistry registry) {// ...}}
要在 XML 配置中做同样的事情,请使用以下方法:
<?xml version="1.0" encoding="UTF-8"?><beans xmlns="http://www.springframework.org/schema/beans"xmlns:mvc="http://www.springframework.org/schema/mvc"xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xsi:schemaLocation="http://www.springframework.org/schema/beanshttps://www.springframework.org/schema/beans/spring-beans.xsdhttp://www.springframework.org/schema/mvchttps://www.springframework.org/schema/mvc/spring-mvc.xsd"><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></beans>
下面一个使用 @DateTimeFormat 的例子
@GetMapping("/data")public String data(@DateTimeFormat(pattern = "yyyy-MM-dd") Date date)
默认情况下,Spring MVC 在解析和格式化日期值时考虑了请求的地域性。这适用于日期被表示为字符串的 「input」表单字段。然而,对于 「date」和 「time」表单字段,浏览器使用 HTML 规范中定义的固定格式。在这种情况下,日期和时间的格式化可以按以下方式定制。
@Configuration@EnableWebMvcpublic class WebConfig implements WebMvcConfigurer {@Overridepublic void addFormatters(FormatterRegistry registry) {// 这个是对 java.time(jdk8 的时间 api) 时间相关的格式化,比如 Duration、DataTime 等时间对象DateTimeFormatterRegistrar registrar = new DateTimeFormatterRegistrar();registrar.setUseIsoFormat(true);registrar.registerFormatters(registry);}}
:::info 参见 FormatterRegistrar SPI 和 FormattingConversionServiceFactoryBean,以了解更多关于何时使用 FormatterRegistrar 实现的信息。 :::
