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

Spring Boot SpringDoc Swagger:如何将LocalTime请求参数设为string($time)

解决Swagger中LocalTime参数显示为string($date-time)而非string($time)的问题

针对你遇到的@DateTimeFormat(iso = DateTimeFormat.ISO.TIME)标注的LocalTime请求参数在Swagger中显示异常的问题,提供以下两种解决方案:

方案一:单个参数手动指定Schema

直接在目标参数上添加@Schema注解,明确指定参数的类型和格式:

@RequestParam(value = "end_time", required = false)
@DateTimeFormat(iso = DateTimeFormat.ISO.TIME)
@Schema(type = "string", format = "time")
LocalTime endTime

添加该注解后,Swagger会将该参数渲染为string($time),和LocalDate搭配@DateTimeFormat(iso = DateTimeFormat.ISO.DATE)的显示效果保持一致。

方案二:全局配置统一处理所有LocalTime参数

如果项目中有大量LocalTime类型的参数需要统一处理,可以创建SpringDoc全局配置类,自定义Schema映射:

import io.swagger.v3.oas.models.media.Schema;
import org.springdoc.core.customizers.OpenApiCustomizer;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import java.time.LocalTime;

@Configuration
public class SpringDocCustomConfig {

    @Bean
    public OpenApiCustomizer localTimeSchemaCustomizer() {
        return openApi -> {
            Schema<?> timeSchema = new Schema<>();
            timeSchema.setType("string");
            timeSchema.setFormat("time");
            openApi.getComponents().getSchemas().put(LocalTime.class.getSimpleName(), timeSchema);
        };
    }
}

这个配置会让所有LocalTime类型的参数在Swagger中统一显示为string($time),无需逐个参数添加注解。

原因说明

springdoc-openapi对LocalDate默认适配了date格式,但对LocalTime的默认映射逻辑是关联到date-time格式,因此需要通过上述方式手动修正格式映射。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.11 03:35:18