Spring 3.0.5自定义转换器无法全局作用于控制器的问题求助
解决方案:Spring 3.0.5 全局生效自定义转换器/编辑器
针对你遇到的自定义转换器在控制器中不生效的问题,以下是适配Spring 3.0.5版本的可行方案:
方案1:修正全局FormattingConversionService配置
Spring MVC 3.0.x中,<mvc:annotation-driven>默认使用FormattingConversionService作为数据绑定的转换服务,因此必须确保你的自定义转换器注册到这个类型的实例中,同时注意上下文分层的细节:
正确XML配置
<!-- 1. 定义带自定义转换器的FormattingConversionService --> <bean id="conversionService" class="org.springframework.format.support.FormattingConversionServiceFactoryBean"> <property name="converters"> <set> <bean class="org.example.impl.StringToMYTypeConverter" /> </set> </property> </bean> <!-- 2. 明确指定mvc注解驱动使用上述转换服务 --> <mvc:annotation-driven conversion-service="conversionService" />
关键排查点
- 确保
conversionService的bean定义在<mvc:annotation-driven>之前,Spring需要先初始化该bean才能被引用。 - 检查是否存在多个
<mvc:annotation-driven>配置,后续配置会覆盖前面的,导致自定义转换服务失效。 - 确认
conversionService和<mvc:annotation-driven>在同一个上下文(通常是DispatcherServlet的上下文,如dispatcher-servlet.xml),避免root上下文和servlet上下文的分层引用问题。
方案2:全局注册PropertyEditor(无需修改ConversionService)
如果转换服务配置仍未生效,可以通过PropertyEditorRegistrar实现全局编辑器注册,所有控制器的WebDataBinder都会自动应用:
步骤1:实现PropertyEditorRegistrar
public class CustomPropertyEditorRegistrar implements PropertyEditorRegistrar { @Override public void registerCustomEditors(PropertyEditorRegistry registry) { // 注册自定义编辑器,替换为你的PropertyEditor实现 registry.registerCustomEditor(MYType.class, new StringToMYTypeConverter()); } }
步骤2:配置全局WebBindingInitializer
<bean id="customBindingInitializer" class="org.springframework.web.bind.support.ConfigurableWebBindingInitializer"> <property name="propertyEditorRegistrars"> <list> <bean class="org.example.impl.CustomPropertyEditorRegistrar" /> </list> </property> </bean> <!-- 将绑定初始化器关联到mvc注解驱动 --> <mvc:annotation-driven web-binding-initializer="customBindingInitializer" />
额外验证点
- 确认
StringToMYTypeConverter实现了正确的接口:作为转换器需实现org.springframework.core.convert.converter.Converter<String, MYType>;作为PropertyEditor需继承java.beans.PropertyEditorSupport。 - 调试时可在
FormattingConversionServiceFactoryBean的afterPropertiesSet()方法中添加日志,验证自定义转换器是否被成功注册。 - 检查是否有其他自动创建的
ConversionService实例覆盖了你的自定义bean,可通过ApplicationContext.getBeansOfType(ConversionService.class)查看所有实例。
内容的提问来源于stack exchange,提问作者David Balažic
相关产品推荐
相关产品推荐

