SpringMVC 6+源码分析(十)数据绑定与类型转换
本文基于 Spring Framework 6.2.x(Spring Boot 3.4.x 所对应版本)源码编写,源码为开源项目 spring-projects/spring-framework(Apache 2.0 协议),文中引用均为学习目的的片段摘录,版权归原项目作者所有。
上一篇我们分析了异常处理体系,标准异常映射表里有一行 TypeMismatchException 映射到 400,而参数解析阶段抛出的 MethodArgumentTypeMismatchException 是它的子类------这类"参数类型对不上"的异常,源头正是本文要展开的数据绑定与类型转换环节。我们写 Controller 时,除了(六)里讲过的 @RequestParam 直接取值,还有一类很常见的"对象参数":一个没有任何注解的 POJO,表单里十几个参数是怎么恰好塞进它各个字段、还顺便把字符串转成了 Integer、LocalDateTime 的?
本文我们就顺着这条"参数 → 对象"的链路往下看,也就是 WebDataBinder 与 Converter 体系。
一、概述
先回顾一下位置。(六)参数处理里我们说过,RequestMappingHandlerAdapter 遍历 HandlerMethodArgumentResolverComposite 选参数解析器,@RequestParam、@PathVariable、@RequestHeader 这些单值参数由对应注解解析器直接取值并做单次类型转换。但对象参数走的是另一条路------兜底的 ServletModelAttributeMethodProcessor,它不直接取值,而是创建一个 WebDataBinder,把整个请求的参数列表一次性"绑"到目标对象上:
java
@Override
public boolean supportsParameter(MethodParameter parameter) {
return (parameter.hasParameterAnnotation(ModelAttribute.class) ||
(this.annotationNotRequired && !BeanUtils.isSimpleProperty(parameter.getParameterType())));
}
判断条件有两个:参数上标了 @ModelAttribute,或者(annotationNotRequired = true 的兜底模式下)参数不是简单类型 。所谓简单类型,是 BeanUtils.isSimpleProperty() 的定义------基本类型及其包装类、String、Number、Date、集合、数组等;我们自己写的表单 POJO 不在此列,所以哪怕一个注解都不加,也会被它接管。
用一张图标注出数据绑定在 doDispatch() 执行流程中的位置:

那 WebDataBinder 到底负责什么?一句话概括四件事:收集参数值(MutablePropertyValues)、按字段名把值写到对象属性上(属性绑定)、把 String 转成目标字段类型(类型转换)、把绑定失败和校验失败收集成 BindingResult 。其中类型转换是本文的主菜------它背后是 Spring 的 Converter / Formatter 双体系,配上一条更古老的 PropertyEditor 轨道,三者如何分工、谁先谁后,就是接下来要回答的问题。
二、类型转换体系
2.1 三套体系对比
Spring 里做类型转换有三套并存的机制,先把它们放在一起看:
| 体系 | 核心接口 | 模块/包 | 方向 | 特点 |
|---|---|---|---|---|
| PropertyEditor(旧轨) | java.beans.PropertyEditor |
JDK + spring-beans | 只能 String → 目标类型 |
JavaBeans 时代产物,有状态(每次绑定要新实例),只能处理"文本转对象" |
| Converter(新轨) | org.springframework.core.convert.converter.Converter<S, T> |
spring-core | 任意 S → 任意 T | 类型安全、无状态、函数式,Spring 3.0 引入的统一转换门面 |
| Formatter(格式化) | org.springframework.format.Formatter<T> |
spring-context | String ↔ T 双向 |
面向"字段的展示与解析",感知 Locale,专攻日期、数字、金额的格式化场景 |
三者不是替代关系:Converter 是底座,Formatter 是它在"文本 ↔ 对象"场景下的格式化特化,而 PropertyEditor 是历史包袱但至今仍在绑定流程里扮演角色(3.3 节会看到它作为回退轨道)。最终这三套机制被 ConversionService / FormatterRegistry 统一收编。
2.2 Converter / ConverterFactory / ConverterRegistry
先看主角 Converter,接口位于 spring-core 模块的 org.springframework.core.convert.converter 包下:
java
@FunctionalInterface
public interface Converter<S, T> {
/**
* Convert the source object of type {@code S} to target type {@code T}.
* @param source the source object to convert, which must be an instance of {@code S} (never {@code null})
* @return the converted object, which must be an instance of {@code T} (potentially {@code null})
* @throws IllegalArgumentException if the source cannot be converted to the desired target type
*/
@Nullable
T convert(S source);
/**
* Construct a composed {@link Converter} that first applies this {@link Converter}
* to its input, and then applies the {@code after} {@link Converter} to the
* result.
* // ...(javadoc 略)
* @since 5.3
*/
default <U> Converter<S, U> andThen(Converter<? super T, ? extends U> after) {
Assert.notNull(after, "'after' Converter must not be null");
return (S s) -> {
T initialResult = convert(s);
return (initialResult != null ? after.convert(initialResult) : null);
};
}
}
带两个泛型参数 S(源类型)和 T(目标类型),本身就是函数式接口,写起来就是一行 lambda;andThen 提供管道式组合。类型信息全在泛型上,编译期就能检查,这是它对比 PropertyEditor 最大的进步。
如果要按"一族类型"注册转换器,比如 String → 所有枚举,逐个写 Converter 太啰嗦,这时用 ConverterFactory:
java
public interface ConverterFactory<S, R> {
/**
* Get the converter to convert from S to target type T, where T is also an instance of R.
* @param <T> the target type
* @param targetType the target type to convert to
* @return a converter from S to T
*/
<T extends R> Converter<S, T> getConverter(Class<T> targetType);
}
S 是固定的源类型,R 是目标类型的上界(比如 Enum),运行时根据实际要转到的 targetType 临时取一个 Converter------经典的工厂模式。
而注册和查找这些转换器的地方是 ConverterRegistry,看它的实现类 GenericConversionService 的注册段:
java
@Override
public void addConverter(Converter<?, ?> converter) {
ResolvableType[] typeInfo = getRequiredTypeInfo(converter.getClass(), Converter.class);
if (typeInfo == null && converter instanceof DecoratingProxy decoratingProxy) {
typeInfo = getRequiredTypeInfo(decoratingProxy.getDecoratedClass(), Converter.class);
}
if (typeInfo == null) {
throw new IllegalArgumentException("Unable to determine source type <S> and target type <T> for your " +
"Converter [" + converter.getClass().getName() + "]; does the class parameterize those types?");
}
addConverter(new ConverterAdapter(converter, typeInfo[0], typeInfo[1]));
}
@Override
public <S, T> void addConverter(Class<S> sourceType, Class<T> targetType, Converter<? super S, ? extends T> converter) {
addConverter(new ConverterAdapter(
converter, ResolvableType.forClass(sourceType), ResolvableType.forClass(targetType)));
}
@Override
public void addConverter(GenericConverter converter) {
this.converters.add(converter);
invalidateCache();
}
@Override
public void addConverterFactory(ConverterFactory<?, ?> factory) {
// ...(略)同样反射解析泛型,包装成 ConverterFactoryAdapter
}
注意第一个方法:注册时通过反射 getRequiredTypeInfo() 读出实现类上的 <S, T> 泛型实参,包装成带类型配对的 ConverterAdapter------这就是为什么我们自定义 Converter 必须写明泛型,匿名 lambda 直接 addConverter 时要用三参数重载显式给类型。
2.3 Formatter 与 FormatterRegistry
再看到格式化这条线。Formatter 接口本身非常短:
java
public interface Formatter<T> extends Printer<T>, Parser<T> {
}
它是两个 @FunctionalInterface 的组合接口,各只有一个方法:
java
@FunctionalInterface
public interface Printer<T> {
String print(T object, Locale locale);
}
@FunctionalInterface
public interface Parser<T> {
T parse(String text, Locale locale) throws ParseException;
}
print 负责"对象 → 文本"(用于展示、回填表单),parse 负责"文本 → 对象"(用于绑定入参),都带 Locale 参数------这就是它与 Converter 的本质区别:Converter 是纯类型转换,Formatter 是带国际化语义的双向格式化 。@DateTimeFormat、@NumberFormat 注解背后跑的都是 Formatter。
接收 Formatter 的注册口是 FormatterRegistry,它继承自 ConverterRegistry:
java
public interface FormatterRegistry extends ConverterRegistry {
void addPrinter(Printer<?> printer);
void addParser(Parser<?> parser);
void addFormatter(Formatter<?> formatter);
void addFormatterForFieldType(Class<?> fieldType, Formatter<?> formatter);
void addFormatterForFieldType(Class<?> fieldType, Printer<?> printer, Parser<?> parser);
void addFormatterForFieldAnnotation(AnnotationFormatterFactory<? extends Annotation> annotationFormatterFactory);
}
几个注册方式的分工:addFormatter* 按"类型"注册,addFormatterForFieldAnnotation 按"注解"注册(AnnotationFormatterFactory 会根据字段上标了什么注解、字段是什么类型,动态产出一个 Formatter),最后一族就是 @DateTimeFormat 生效的通道,3.5 节会用它。
2.4 ConversionService 与默认注册的转换器
收编两条线的门面是 ConversionService 接口(canConvert + convert),核心实现是 GenericConversionService。看它的转换入口:
java
@SuppressWarnings("unchecked")
@Override
@Nullable
public <T> T convert(@Nullable Object source, Class<T> targetType) {
Assert.notNull(targetType, "Target type to convert to cannot be null");
return (T) convert(source, TypeDescriptor.forObject(source), TypeDescriptor.valueOf(targetType));
}
@Override
@Nullable
public Object convert(@Nullable Object source, @Nullable TypeDescriptor sourceType, TypeDescriptor targetType) {
Assert.notNull(targetType, "Target type to convert to cannot be null");
if (sourceType == null) {
Assert.isTrue(source == null, "Source must be [null] if source type == [null]");
return handleResult(null, targetType, convertNullSource(null, targetType));
}
if (source != null && !sourceType.getObjectType().isInstance(source)) {
throw new IllegalArgumentException("Source to convert from must be an instance of [" +
sourceType + "]; instead it was a [" + source.getClass().getName() + "]");
}
GenericConverter converter = getConverter(sourceType, targetType);
if (converter != null) {
Object result = ConversionUtils.invokeConverter(converter, source, sourceType, targetType);
return handleResult(sourceType, targetType, result);
}
return handleConverterNotFound(source, sourceType, targetType);
}
转换时传入的是 TypeDescriptor------它不只是个 Class,还携带字段上的注解、泛型参数等上下文,所以转换器能拿到"这个字段标了 @DateTimeFormat(pattern=...)"这类信息。查找转换器的方法值得多看一眼:
java
@Nullable
protected GenericConverter getConverter(TypeDescriptor sourceType, TypeDescriptor targetType) {
ConverterCacheKey key = new ConverterCacheKey(sourceType, targetType);
GenericConverter converter = this.converterCache.get(key);
if (converter != null) {
return (converter != NO_MATCH ? converter : null);
}
converter = this.converters.find(sourceType, targetType);
if (converter == null) {
converter = getDefaultConverter(sourceType, targetType);
}
if (converter != null) {
this.converterCache.put(key, converter);
return converter;
}
this.converterCache.put(key, NO_MATCH);
return null;
}
查找结果(包括"找不到"这个结论,以 NO_MATCH 哨兵形式)会缓存进 ConcurrentReferenceHashMap------类型对(sourceType → targetType)的查找在高并发请求下是热路径,Spring 用缓存避免了每次遍历注册表。
再看到 SpringBoot 环境下实际用的服务是什么。DefaultFormattingConversionService 在 GenericConversionService 基础上预装了"大多数应用都够用"的一套转换器:
java
public DefaultFormattingConversionService(
@Nullable StringValueResolver embeddedValueResolver, boolean registerDefaultFormatters) {
if (embeddedValueResolver != null) {
setEmbeddedValueResolver(embeddedValueResolver);
}
DefaultConversionService.addDefaultConverters(this);
if (registerDefaultFormatters) {
addDefaultFormatters(this);
}
}
两步走:DefaultConversionService.addDefaultConverters() 装载基础转换器(数字、枚举、字符、集合/数组/Map 的元素级转换等一整套),addDefaultFormatters() 装载格式化器:
java
public static void addDefaultFormatters(FormatterRegistry formatterRegistry) {
// Default handling of number values
formatterRegistry.addFormatterForFieldAnnotation(new NumberFormatAnnotationFormatterFactory());
// Default handling of monetary values
if (jsr354Present) {
formatterRegistry.addFormatter(new CurrencyUnitFormatter());
formatterRegistry.addFormatter(new MonetaryAmountFormatter());
formatterRegistry.addFormatterForFieldAnnotation(new Jsr354NumberFormatAnnotationFormatterFactory());
}
// Default handling of date-time values
// just handling JSR-310 specific date and time types
new DateTimeFormatterRegistrar().registerFormatters(formatterRegistry);
// regular DateFormat-based Date, Calendar, Long converters
new DateFormatterRegistrar().registerFormatters(formatterRegistry);
}
用表格整理默认注册的内容:
| 注册来源 | 注册的内容 | 覆盖场景 |
|---|---|---|
| DefaultConversionService.addDefaultConverters | 标量转换器全家桶(String↔Number/Enum/Boolean/Character、集合/数组/Map 元素转换等) | 日常一切"能转就转"的基础转换 |
| NumberFormatAnnotationFormatterFactory | @NumberFormat 注解 → 数字 Formatter |
字段标注解的数字格式化 |
| DateTimeFormatterRegistrar | JSR-310 的 LocalDate/LocalTime/LocalDateTime 等 Formatter + @DateTimeFormat 支持 |
日期类型绑定(3.5 节主角) |
| DateFormatterRegistrar | java.util.Date、Calendar、Long 的转换 |
老式日期类型 |
| JSR-354(类路径有 javax.money 时) | 金额相关 Formatter | MonetaryAmount 字段 |
整套体系的结构用类图表示如下:

三、源码解析过程
回顾完体系,接下来把"一个表单 POJO 参数"从请求到入参的完整生命周期走一遍:binder 是怎么创建的、绑定是怎么执行的、转换是怎么在两条轨道之间挑选的。
3.1 WebDataBinder 的创建
入口是(六)里出现过的兜底解析器 ServletModelAttributeMethodProcessor,它继承 spring-web 模块的 ModelAttributeMethodProcessor,resolveArgument() 的主干如下:
java
@Override
@Nullable
public final Object resolveArgument(MethodParameter parameter, @Nullable ModelAndViewContainer mavContainer,
NativeWebRequest webRequest, @Nullable WebDataBinderFactory binderFactory) throws Exception {
Assert.state(mavContainer != null, "ModelAttributeMethodProcessor requires ModelAndViewContainer");
Assert.state(binderFactory != null, "ModelAttributeMethodProcessor requires WebDataBinderFactory");
String name = ModelFactory.getNameForParameter(parameter);
ModelAttribute ann = parameter.getParameterAnnotation(ModelAttribute.class);
if (ann != null) {
mavContainer.setBinding(name, ann.binding());
}
Object attribute;
BindingResult bindingResult = null;
if (mavContainer.containsAttribute(name)) {
// ...(略)@ModelAttribute 方法提前放进 model 的对象,直接复用
}
else {
try {
// Mainly to allow subclasses alternative to create attribute
attribute = createAttribute(name, parameter, binderFactory, webRequest);
}
catch (MethodArgumentNotValidException ex) {
// ...(略)构造器绑定失败的处理
}
}
// No BindingResult yet, proceed with binding and validation
if (bindingResult == null) {
ResolvableType type = ResolvableType.forMethodParameter(parameter);
WebDataBinder binder = binderFactory.createBinder(webRequest, attribute, name, type);
if (attribute == null) {
constructAttribute(binder, webRequest);
attribute = wrapAsOptionalIfNecessary(parameter, binder.getTarget());
}
if (!binder.getBindingResult().hasErrors()) {
if (!mavContainer.isBindingDisabled(name)) {
bindRequestParameters(binder, webRequest);
}
validateIfApplicable(binder, parameter);
}
if (binder.getBindingResult().hasErrors() && isBindExceptionRequired(binder, parameter)) {
throw new MethodArgumentNotValidException(parameter, binder.getBindingResult());
}
// Value type adaptation, also covering java.util.Optional
if (!parameter.getParameterType().isInstance(attribute)) {
attribute = binder.convertIfNecessary(binder.getTarget(), parameter.getParameterType(), parameter);
}
bindingResult = binder.getBindingResult();
}
// Add resolved attribute and BindingResult at the end of the model
Map<String, Object> bindingResultModel = bindingResult.getModel();
mavContainer.removeAttributes(bindingResultModel);
mavContainer.addAllAttributes(bindingResultModel);
return attribute;
}
主干四步:先看 model 里有没有现成对象可复用(@ModelAttribute 方法提前放进去的);没有就创建 binder 并实例化目标对象;然后 bindRequestParameters() 执行绑定、validateIfApplicable() 执行校验;最后把对象和 BindingResult 一起放回 model ------这就是为什么 Controller 方法参数后面可以再跟一个 Errors/BindingResult 参数接收绑定错误(isBindExceptionRequired 就是判断下一个参数是不是它,是就不抛异常)。
binderFactory.createBinder() 是这条链的枢纽。工厂接口的实现链是:DefaultDataBinderFactory 定义骨架,InitBinderDataBinderFactory 加上 @InitBinder 支持,ServletRequestDataBinderFactory 负责实例化 Servlet 环境的 binder。先看骨架:
java
@Override
public final WebDataBinder createBinder(
NativeWebRequest webRequest, @Nullable Object target, String objectName,
ResolvableType type) throws Exception {
return createBinderInternal(webRequest, target, objectName, type);
}
private WebDataBinder createBinderInternal(
NativeWebRequest webRequest, @Nullable Object target, String objectName,
@Nullable ResolvableType type) throws Exception {
WebDataBinder dataBinder = createBinderInstance(target, objectName, webRequest);
dataBinder.setNameResolver(new BindParamNameResolver());
if (target == null && type != null) {
dataBinder.setTargetType(type);
}
if (this.initializer != null) {
this.initializer.initBinder(dataBinder);
}
initBinder(dataBinder, webRequest);
// ...(略)6.1 起的方法级校验初始化
}
创建 binder 的过程中做了两类"初始化注入":initializer.initBinder(dataBinder) 是全局的 WebBindingInitializer(SpringBoot 在这里把全局 ConversionService 塞进去,3.4 节细说),initBinder(dataBinder, webRequest) 则是执行用户声明的 @InitBinder 方法。看这个方法的实现:
java
@Override
public void initBinder(WebDataBinder dataBinder, NativeWebRequest request) throws Exception {
for (InvocableHandlerMethod binderMethod : this.binderMethods) {
if (isBinderMethodApplicable(binderMethod, dataBinder)) {
Object returnValue = binderMethod.invokeForRequest(request, null, dataBinder);
if (returnValue != null) {
throw new IllegalStateException(
"@InitBinder methods must not return a value (should be void): " + binderMethod);
}
}
}
}
/**
* Determine whether the given {@code @InitBinder} method should be used
* to initialize the given {@link WebDataBinder} instance. By default we
* check the specified attribute names in the annotation value, if any.
*/
protected boolean isBinderMethodApplicable(HandlerMethod initBinderMethod, WebDataBinder dataBinder) {
InitBinder ann = initBinderMethod.getMethodAnnotation(InitBinder.class);
Assert.state(ann != null, "No InitBinder annotation");
String[] names = ann.value();
return (ObjectUtils.isEmpty(names) || ObjectUtils.containsElement(names, dataBinder.getObjectName()));
}
这段解释了 @InitBinder 的全部规则:每个 binder 创建出来后,Controller 里(以及 @ControllerAdvice 里的)所有 @InitBinder 方法会被挨个检查,注解没写 value 或 value 包含当前对象名(getObjectName(),默认是 "target",类名首字母小写)的才会执行;方法以 binder 为实参被反射调用,必须返回 void 。所以我们在 @InitBinder 方法里 binder.registerCustomEditor(...) 注册的编辑器,只对"匹配对象名的这批 binder"生效------这就是局部编辑器的原理。
最后看子类 ServletRequestDataBinderFactory,它非常小,职责就是决定 binder 的具体类型:
java
public class ServletRequestDataBinderFactory extends InitBinderDataBinderFactory {
/**
* Create a new instance.
* @param binderMethods one or more {@code @InitBinder} methods
* @param initializer provides global data binder initialization
*/
public ServletRequestDataBinderFactory(@Nullable List<InvocableHandlerMethod> binderMethods,
@Nullable WebBindingInitializer initializer) {
super(binderMethods, initializer);
}
/**
* Returns an instance of {@link ExtendedServletRequestDataBinder}.
*/
@Override
protected ServletRequestDataBinder createBinderInstance(
@Nullable Object target, String objectName, NativeWebRequest request) throws Exception {
return new ExtendedServletRequestDataBinder(target, objectName);
}
}
ExtendedServletRequestDataBinder 又是 ServletRequestDataBinder 的子类,差异只在重写的 addBindValues():把 URI 模板变量和请求头也加进待绑定的值里(常见的敏感头如 cookie、host 会被过滤掉)。
3.2 绑定执行
binder 创建好了,回到 resolveArgument() 的第 11 行 bindRequestParameters(binder, webRequest)。这是父类留的扩展点,Servlet 子类把它落到 ServletRequestDataBinder#bind() 上:
java
@Override
protected void constructAttribute(WebDataBinder binder, NativeWebRequest request) {
ServletRequest servletRequest = request.getNativeRequest(ServletRequest.class);
Assert.state(servletRequest != null, "No ServletRequest");
ServletRequestDataBinder servletBinder = (ServletRequestDataBinder) binder;
servletBinder.construct(servletRequest);
}
@Override
protected void bindRequestParameters(WebDataBinder binder, NativeWebRequest request) {
ServletRequest servletRequest = request.getNativeRequest(ServletRequest.class);
Assert.state(servletRequest != null, "No ServletRequest");
ServletRequestDataBinder servletBinder = (ServletRequestDataBinder) binder;
servletBinder.bind(servletRequest);
}
注意两个方法都干了把 WebDataBinder 强转为 ServletRequestDataBinder 的事:constructAttribute 是 6.1 引入的"构造器绑定"(目标对象只有有参构造时,直接用请求参数解析构造实参,record 类就是受益者);bindRequestParameters 则是传统的 setter 绑定。看到后者最终调用的 bind():
java
public void bind(ServletRequest request) {
if (shouldNotBindPropertyValues()) {
return;
}
MutablePropertyValues mpvs = new ServletRequestParameterPropertyValues(request);
MultipartRequest multipartRequest = WebUtils.getNativeRequest(request, MultipartRequest.class);
if (multipartRequest != null) {
bindMultipart(multipartRequest.getMultiFileMap(), mpvs);
}
else if (isFormDataPost(request)) {
HttpServletRequest httpServletRequest = WebUtils.getNativeRequest(request, HttpServletRequest.class);
if (httpServletRequest != null && HttpMethod.POST.matches(httpServletRequest.getMethod())) {
StandardServletPartUtils.bindParts(httpServletRequest, mpvs, isBindEmptyMultipartFiles());
}
}
addBindValues(mpvs, request);
doBind(mpvs);
}
第一步 new ServletRequestParameterPropertyValues(request) 把请求里所有参数收进一个 MutablePropertyValues------它本质是"属性名 → 属性值"的列表,支持 user.address.city 这种嵌套路径和 hobbies[0] 这种集合下标。多文件上传、Part、子类的附加值(URI 变量、请求头)都往这个列表里补,最后 doBind() 交给父类 DataBinder:
java
public void bind(PropertyValues pvs) {
if (shouldNotBindPropertyValues()) {
return;
}
MutablePropertyValues mpvs = (pvs instanceof MutablePropertyValues mutablePropertyValues ?
mutablePropertyValues : new MutablePropertyValues(pvs));
doBind(mpvs);
}
java
protected void doBind(MutablePropertyValues mpvs) {
checkAllowedFields(mpvs);
checkRequiredFields(mpvs);
applyPropertyValues(mpvs);
}
doBind() 三步。checkAllowedFields 按 allowedFields/disallowedFields 白黑名单过滤(这是防"批量绑定漏洞"的机制,不在白名单里的字段直接从列表里移除并记成 suppressed field);checkRequiredFields 检查必填字段;然后是真正写值的 applyPropertyValues():
java
protected void applyPropertyValues(MutablePropertyValues mpvs) {
try {
// Bind request parameters onto target object.
getPropertyAccessor().setPropertyValues(mpvs, isIgnoreUnknownFields(), isIgnoreInvalidFields());
}
catch (PropertyBatchUpdateException ex) {
// Use bind error processor to create FieldErrors.
for (PropertyAccessException pae : ex.getPropertyAccessExceptions()) {
getBindingErrorProcessor().processPropertyAccessException(pae, getInternalBindingResult());
}
}
}
getPropertyAccessor() 拿到的是 BeanWrapper(Bean 属性访问器,注入依赖用的同一套基础设施),setPropertyValues() 按 setter/字段逐个写值------而"写值"的前提是先把 String 转成字段类型,这正是下一步 TypeConverterDelegate 的工作。绑定过程中任何一处转换失败,都会被收集成 PropertyAccessException(典型如 typeMismatch 错误码),而不是直接中断整个请求------错误统一进 BindingResult。
完整的执行链路用时序图表示:

3.3 类型转换双轨
重头戏来了。BeanWrapper 写每个属性时都会走到 TypeConverterDelegate#convertIfNecessary(),这是整个转换体系与绑定流程的汇合点,方法比较长,分段看:
第一段,轨道选择:
java
@SuppressWarnings("unchecked")
@Nullable
public <T> T convertIfNecessary(@Nullable String propertyName, @Nullable Object oldValue, @Nullable Object newValue,
@Nullable Class<T> requiredType, @Nullable TypeDescriptor typeDescriptor) throws IllegalArgumentException {
// Custom editor for this type?
PropertyEditor editor = this.propertyEditorRegistry.findCustomEditor(requiredType, propertyName);
ConversionFailedException conversionAttemptEx = null;
// No custom editor but custom ConversionService specified?
ConversionService conversionService = this.propertyEditorRegistry.getConversionService();
if (editor == null && conversionService != null && newValue != null && typeDescriptor != null) {
TypeDescriptor sourceTypeDesc = TypeDescriptor.forObject(newValue);
if (conversionService.canConvert(sourceTypeDesc, typeDescriptor)) {
try {
return (T) conversionService.convert(newValue, sourceTypeDesc, typeDescriptor);
}
catch (ConversionFailedException ex) {
// fallback to default conversion logic below
conversionAttemptEx = ex;
}
}
}
优先级一目了然:
- 先找针对该字段/该类型注册的自定义
PropertyEditor(@InitBinder里registerCustomEditor注册的就是它)------找到了就用它,ConversionService 直接靠边; - 没有自定义 editor 且配了 ConversionService,就先走 ConversionService (
canConvert通过后convert,字段注解等上下文都在TypeDescriptor里); - ConversionService 转换失败时不抛出 ,把异常暂存到
conversionAttemptEx,落到下面的回退逻辑。
第二段,回退到 PropertyEditor 轨道:
java
Object convertedValue = newValue;
// Value not of required type?
if (editor != null || (requiredType != null && !ClassUtils.isAssignableValue(requiredType, convertedValue))) {
// ...(略)集合/数组元素的 editor 查找
if (editor == null) {
editor = findDefaultEditor(requiredType);
}
convertedValue = doConvertValue(oldValue, convertedValue, requiredType, editor);
}
doConvertValue() 内部调 editor.setAsText() 完成转换。注意 findDefaultEditor() 还能按类型匹配 JDK 内建的 editor(如 ClassEditor、URLEditor),Spring 在 PropertyEditorRegistrySupport 里预注册了一批默认 editor。
第三段,两轨都没搞定时的最后补救:
java
if (!ClassUtils.isAssignableValue(requiredType, convertedValue)) {
if (conversionAttemptEx != null) {
// Original exception from former ConversionService call above...
throw conversionAttemptEx;
}
else if (conversionService != null && typeDescriptor != null) {
// ConversionService not tried before, probably custom editor found
// but editor couldn't produce the required type...
TypeDescriptor sourceTypeDesc = TypeDescriptor.forObject(newValue);
if (conversionService.canConvert(sourceTypeDesc, typeDescriptor)) {
return (T) conversionService.convert(newValue, sourceTypeDesc, typeDescriptor);
}
}
// ...(略)拼装 "Cannot convert value..." 错误信息并抛出
}
}
if (conversionAttemptEx != null) {
if (editor == null && !standardConversion && requiredType != null && Object.class != requiredType) {
throw conversionAttemptEx;
}
logger.debug("Original ConversionService attempt failed - ignored since " +
"PropertyEditor based conversion eventually succeeded", conversionAttemptEx);
}
return (T) convertedValue;
}
兜底规则很绕但很有味道:ConversionService 失败后如果 PropertyEditor 也没能产出正确类型,且之前确实尝试过 ConversionService,就把那次异常重新抛出(throw conversionAttemptEx);反过来,如果有自定义 editor 但 editor 产出的类型不对,还会再试一次 ConversionService。双轨互为备份,自定义 editor 优先级最高 ------这解释了一个常见困惑:@InitBinder 里注册的 PropertyEditor 会"压住"全局 Converter,因为 editor != null 时第一步的 ConversionService 分支整个被短路。
另外方法中间还有一段"标准转换规则"(String 构造器、枚举名匹配、Number 提升、集合元素转换等),是在两条轨道都没命中时的第三层兜底,比如目标类型有 (String) 构造器就直接反射调用------ClassUtils.isAssignableValue 系列判断加上这些规则,保证了哪怕什么都没注册,简单的转换也能工作。
3.4 自定义转换器注册
双轨机制讲完,再看自定义转换器是怎么"上车"的。扩展口是 WebMvcConfigurer 的这个默认方法:
java
/**
* Add {@link Converter Converters} and {@link Formatter Formatters} in addition to the ones
* registered by default.
*/
default void addFormatters(FormatterRegistry registry) {
}
默认空实现。那这个 registry 到底是哪个实例?回调又由谁触发?SpringBoot 环境下看 WebMvcAutoConfiguration:
java
@Bean
@Override
public FormattingConversionService mvcConversionService() {
Format format = this.mvcProperties.getFormat();
WebConversionService conversionService = new WebConversionService(
new DateTimeFormatters().dateFormat(format.getDate())
.timeFormat(format.getTime())
.dateTimeFormat(format.getDateTime()));
addFormatters(conversionService);
return conversionService;
}
这个 @Bean 创建的是 WebConversionService------它继承自 DefaultFormattingConversionService(2.4 节那套默认转换器的底子都在),还按 spring.mvc.format.* 配置项调整了日期时间格式。紧接着的 addFormatters(conversionService) 会触发 Composite 回调,把容器里所有 WebMvcConfigurer#addFormatters 挨个调一遍------我们自己的重写就从这里进来了。SpringBoot 自己的那个适配器实现也值得看一眼:
java
@Override
public void addFormatters(FormatterRegistry registry) {
ApplicationConversionService.addBeans(registry, this.beanFactory);
}
ApplicationConversionService.addBeans() 会把容器里所有 Converter、ConverterFactory、Formatter、GenericConverter 类型的 Bean 挨个注册进 registry ------所以自定义转换器除了 addFormatters 里手动 add,直接标 @Component 也能生效,殊途同归。
最后一个问题:这个 FormattingConversionService Bean 是怎么影响到每次请求的 binder 的?看 WebMvcConfigurationSupport:
java
protected ConfigurableWebBindingInitializer getConfigurableWebBindingInitializer(
FormattingConversionService mvcConversionService, Validator mvcValidator) {
ConfigurableWebBindingInitializer initializer = new ConfigurableWebBindingInitializer();
initializer.setConversionService(mvcConversionService);
initializer.setValidator(mvcValidator);
MessageCodesResolver messageCodesResolver = getMessageCodesResolver();
if (messageCodesResolver != null) {
initializer.setMessageCodesResolver(messageCodesResolver);
}
return initializer;
}
它被装进 ConfigurableWebBindingInitializer,后者作为 RequestMappingHandlerAdapter 的 webBindingInitializer------正是 3.1 节 createBinderInternal() 里 this.initializer.initBinder(dataBinder) 那一步,把 ConversionService 注入每个新建的 binder(binder.setConversionService(...)),于是 TypeConverterDelegate 里 propertyEditorRegistry.getConversionService() 就能拿到它。从 WebMvcConfigurer#addFormatters 到请求绑定的整条链闭环了。
3.5 日期转换实战
把上面所有机制落到最高频的实战场景:前端传 "2025-10-01" 这类字符串,后端字段是日期类型,怎么办?
方案一:@DateTimeFormat 注解(局部,推荐给"个别字段特殊格式")
java
public class OrderQueryForm {
@DateTimeFormat(pattern = "yyyy-MM-dd HH:mm")
private LocalDateTime startTime;
// ...
}
生效原理在 2.4 节那张默认注册表里:DateTimeFormatterRegistrar 把 @DateTimeFormat 的 AnnotationFormatterFactory 注册进了 ConversionService;3.3 节第一步走 ConversionService 时,TypeDescriptor 带着字段注解,工厂据此产出对应 pattern 的 DateTimeFormatter 完成解析。它还能与 spring.mvc.format.date-time 配置项(WebConversionService 构造参数)联动,注解没写 pattern 时用全局配置。
方案二:全局 Converter(推荐给"全站统一格式")
java
@Component
public class StringToLocalDateTimeConverter implements Converter<String, LocalDateTime> {
@Override
public LocalDateTime convert(String source) {
return LocalDateTime.parse(source, DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm"));
}
}
3.4 节说过,@Component 标注后被 ApplicationConversionService.addBeans() 自动收编,全站所有 String → LocalDateTime 的绑定(不止表单对象,@RequestParam 的单值转换同样走 ConversionService)都会经过它。
两个方案的取舍:注解方案粒度细、不同字段不同格式,但每个字段都要标;全局 Converter 一处注册处处生效,但格式被锁死成一种。此外还有第三种------3.1 节讲过的 @InitBinder + registerCustomEditor,它是Controller 级局部的 PropertyEditor 方案,优先级压过全局 Converter,下一节实际跑起来对比。
四、Demo 实战验证
以上机制整理成一个可运行的 SpringBoot 3.4.5 工程(文末有完整代码地址),核心代码如下。
自定义全局 Converter(@Component 自动注册):
java
@Component
public class StringToLocalDateTimeConverter implements Converter<String, LocalDateTime> {
@Override
public LocalDateTime convert(String source) {
return LocalDateTime.parse(source.trim(), DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm"));
}
}
表单对象与 Controller(含 @InitBinder 局部编辑器、校验收集):
java
public class UserForm {
private String name;
private Integer age;
@DateTimeFormat(pattern = "yyyy/MM/dd")
private LocalDate birthday;
private LocalDateTime createdAt;
// getter/setter 略
}
@Controller
public class BindController {
@InitBinder("userForm") // 局部编辑器:只对 objectName 为 userForm 的 binder 生效
public void initAgeBinder(WebDataBinder binder) {
binder.registerCustomEditor(Integer.class, "age", new PropertyEditorSupport() {
@Override
public void setAsText(String text) {
// 自定义规则:"vip18" 这类写法剥掉非数字字符再转数字
setValue(Integer.valueOf(text.replaceAll("\\D", "")));
}
});
}
@PostMapping("/bind/user")
@ResponseBody
public Map<String, Object> bind(UserForm userForm) {
return Map.of(
"name", userForm.getName(),
"age", userForm.getAge(),
"birthday", userForm.getBirthday().toString(),
"createdAt", userForm.getCreatedAt().toString());
}
}
启动后逐个请求验证,结果与源码分析完全对应:
| 请求参数 | 命中的转换轨道 | 结果 |
|---|---|---|
name=陈皮&age=20&birthday=2001-03-15&createdAt=2025-10-01 09:30 |
字段无注解 → ConversionService(全局 Converter) | age:20,birthday:2001-03-15,createdAt:2025-10-01T09:30 |
birthday=2001/03/15 |
字段标 @DateTimeFormat → ConversionService(注解 Formatter) |
birthday:2001-03-15 |
age=vip18 |
@InitBinder 自定义 PropertyEditor → editor 轨道(优先于 ConversionService) |
age:18(非数字字符被剥掉) |
age=abc |
双轨都失败 → typeMismatch 错误 |
400(无 BindingResult 参数时抛 MethodArgumentNotValidException,被(九)的异常链接管) |
birthday=2001-03-15(字段 pattern 是 yyyy/MM/dd) |
注解 Formatter 解析失败 | 400 |
name=陈皮&age=20&extra=x |
未知字段 extra,默认 ignoreUnknownFields=true |
正常绑定,extra 被忽略 |
两个值得注意的实验细节:age=vip18 证明了 @InitBinder 编辑器优先于 全局 Converter(3.3 节 editor != null 短路 ConversionService 的实际效果);而把 @InitBinder 注解的 value 改成别的对象名(或不加该 Controller),age=vip18 立刻失效------对应 3.1 节 isBinderMethodApplicable() 的对象名匹配逻辑。(顺带一提:表单参数里的 + 会被解码成空格,所以自定义规则写成"剥离非数字字符"而不是"剥掉加号"。)
最后用一张图把本文的知识点归纳一下:

五、总结
数据绑定由 ServletModelAttributeMethodProcessor 发起,为对象参数逐请求创建 WebDataBinder(@InitBinder 方法在创建期先行执行),ServletRequestDataBinder 把请求参数收进 MutablePropertyValues 后经 checkAllowedFields → applyPropertyValues 写入目标对象;每个字段写值时由 TypeConverterDelegate 在 PropertyEditor 与 ConversionService 双轨间调度------自定义 editor 优先,ConversionService 主力,失败层层回退。自定义转换器经 WebMvcConfigurer#addFormatters(或直接 @Component)注册进 WebConversionService,随 ConfigurableWebBindingInitializer 注入每个 binder。
下一篇我们分析 doDispatch() 的最后一环------视图渲染与异步请求,看看 mavContainer 里的视图名是怎么变成页面响应的,Callable/DeferredResult 又是怎么让请求线程提前释放的,本阶段到此收尾。
Demo 完整代码 :SpringMVC/10-数据绑定/binding-demo(SpringBoot 3.4.5 + JDK 17,mvn spring-boot:run 启动后按上表逐个请求验证)
专栏往期:
- SpringMVC 6+源码分析(一)初始化流程
- SpringMVC 6+源码分析(二)DispatcherServlet实例化流程 1
- SpringMVC 6+源码分析(三)DispatcherServlet实例化流程 2
- SpringMVC 6+源码分析(四)DispatcherServlet实例化流程 3------HandlerAdapter初始化
- SpringMVC 6+源码分析(五)执行流程
- SpringMVC 6+源码分析(六)参数处理
- SpringMVC 6+源码分析(七)返回值处理
- SpringMVC 6+源码分析(八)拦截器
- SpringMVC 6+源码分析(九)异常处理
本文为「源码学习」专栏系列文章,转载请注明出处。相互学习,共同进步!