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

Spring Data Rest中LocalDate值解析失败求助

问题解决:Spring Data Rest路径中LocalDate解析失败

问题原因

你遇到的解析错误是因为Spring Data Rest处理URL路径里的LocalDate类型主键时,默认日期解析格式和你使用的yyyy-MM-dd不匹配。@JsonFormat和@DateTimeFormat注解仅对请求体JSON或表单参数生效,无法覆盖路径参数的转换逻辑,导致框架用错误格式解析2022-10-18,最终在索引2处(2022后的-位置)解析失败。

解决方案

通过自定义String到LocalDate的转换器,并注册到Spring MVC配置中,强制指定路径参数的日期解析格式。

步骤1:创建自定义转换器

import org.springframework.core.convert.converter.Converter;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;

public class StringToLocalDateConverter implements Converter<String, LocalDate> {

    private static final DateTimeFormatter DATE_FORMATTER = DateTimeFormatter.ofPattern("yyyy-MM-dd");

    @Override
    public LocalDate convert(String dateStr) {
        return LocalDate.parse(dateStr, DATE_FORMATTER);
    }
}

步骤2:注册转换器到Spring配置

创建Web MVC配置类,将自定义转换器加入格式化注册表:

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

@Configuration
public class WebMvcConfig implements WebMvcConfigurer {

    @Override
    public void addFormatters(FormatterRegistry registry) {
        registry.addConverter(new StringToLocalDateConverter());
    }
}

可选:全局配置日期格式(辅助验证)

也可以在application.properties中添加全局日期格式配置作为补充:

spring.mvc.format.date=yyyy-MM-dd

验证

重启应用后,访问http://localhost:8080/parkingsystem/api/calendario-parcheggio/2022-10-18,即可正常解析LocalDate类型主键并返回对应实体数据。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.16 07:35:18