You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

SpringMVC中Controller的@DateTimeFormat注解失效问题求助

非Spring Boot的SpringMVC中@DateTimeFormat对java.util.Date不起作用的原因及解决办法

问题根源

非Spring Boot项目不会自动配置SpringMVC的格式化转换机制,@DateTimeFormat注解生效需要依赖DateTimeFormatAnnotationFormatterFactory被注册到Spring的ConversionService中。传统SpringMVC默认没有启用这个注解驱动的格式化支持,所以框架找不到对应的转换器处理字符串到java.util.Date的转换,进而抛出类型转换异常。

你手动用SimpleDateFormat能成功,是因为自己显式处理了字符串到Date的转换逻辑,但SpringMVC的参数绑定流程里并没有自动加载这个转换逻辑。

解决办法

1. XML配置方式(适用于传统XML驱动的SpringMVC项目)

在SpringMVC配置文件(如spring-mvc.xml)中添加以下配置,注册支持@DateTimeFormat的转换服务:

<!-- 启用注解驱动并指定自定义转换服务 -->
<mvc:annotation-driven conversion-service="conversionService"/>

<!-- 配置ConversionService,注册DateTimeFormat注解的格式化工厂 -->
<bean id="conversionService" class="org.springframework.format.support.FormattingConversionServiceFactoryBean">
    <property name="formatters">
        <set>
            <bean class="org.springframework.format.datetime.DateFormatter"/>
            <!-- 关键:注册支持@DateTimeFormat的工厂类 -->
            <bean class="org.springframework.format.datetime.DateTimeFormatAnnotationFormatterFactory"/>
        </set>
    </property>
</bean>

2. Java配置方式(适用于JavaConfig驱动的SpringMVC项目)

创建WebMvc配置类,实现WebMvcConfigurer接口,重写addFormatters方法注册格式化工厂:

import org.springframework.context.annotation.Configuration;
import org.springframework.format.FormatterRegistry;
import org.springframework.format.datetime.DateTimeFormatAnnotationFormatterFactory;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

@Configuration
public class WebMvcConfig implements WebMvcConfigurer {
    @Override
    public void addFormatters(FormatterRegistry registry) {
        // 注册支持@DateTimeFormat注解的工厂类
        registry.addFormatterForFieldAnnotation(new DateTimeFormatAnnotationFormatterFactory());
    }
}

额外注意

  • 确保@DateTimeFormat指定的模式和请求参数的日期字符串格式完全匹配,比如你用的"yyyy-MM-dd'T'HH:mm:ss.SSSX",要保证请求参数格式如2024-05-20T14:30:00.123+08完全符合。
  • 若项目依赖Joda-Time,需引入spring-context-support依赖,但你使用java.util.Date,上述配置已足够。

内容的提问来源于stack exchange,提问作者chubbsondubs

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.19 03:50:24