对于最新的稳定版本,请使用 Spring Framework 7.0.6!spring-doc.cadn.net.cn

类型转换

默认情况下,已安装各种数字和日期类型的格式化程序,并通过字段上的@NumberFormat@DateTimeFormat支持自定义。spring-doc.cadn.net.cn

要在Java配置中注册自定义格式化程序和转换器,请使用以下方法:spring-doc.cadn.net.cn

@Configuration
@EnableWebMvc
public class WebConfig implements WebMvcConfigurer {

	@Override
	public void addFormatters(FormatterRegistry registry) {
		// ...
	}
}
@Configuration
@EnableWebMvc
class WebConfig : WebMvcConfigurer {

	override fun addFormatters(registry: FormatterRegistry) {
		// ...
	}
}

要在XML配置中执行相同的操作,请使用以下代码:spring-doc.cadn.net.cn

<?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/beans
		https://www.springframework.org/schema/beans/spring-beans.xsd
		http://www.springframework.org/schema/mvc
		https://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>

默认情况下,Spring MVC 在解析和格式化日期值时会考虑请求的区域设置。这对于日期以字符串形式表示的表单有效,这些字符串使用“input”表单字段。然而,对于“date”和“time”表单字段,浏览器使用 HTML 规范中定义的固定格式。对于此类情况,可以如下自定义日期和时间格式:spring-doc.cadn.net.cn

@Configuration
@EnableWebMvc
public class WebConfig implements WebMvcConfigurer {

	@Override
	public void addFormatters(FormatterRegistry registry) {
		DateTimeFormatterRegistrar registrar = new DateTimeFormatterRegistrar();
		registrar.setUseIsoFormat(true);
		registrar.registerFormatters(registry);
     	}
}
@Configuration
@EnableWebMvc
class WebConfig : WebMvcConfigurer {

	override fun addFormatters(registry: FormatterRegistry) {
		val registrar = DateTimeFormatterRegistrar()
		registrar.setUseIsoFormat(true)
		registrar.registerFormatters(registry)
	}
}
请参阅the FormatterRegistrar SPIFormattingConversionServiceFactoryBean以获取有关何时使用FormatterRegistrar实现的更多信息。