Spring Boot OpenAPI文档中LocalDateTime字段示例值无法显示求助
解决Springdoc OpenAPI 2.1.0中LocalDateTime字段自定义示例不显示的问题
问题场景
使用Spring Boot 3 + Springdoc OpenAPI 2.1.0时,为LocalDateTime字段添加@Schema(example="xxx")注解后,生成的OpenAPI文档仍显示默认的$date-time而非自定义示例值。
解决方案
方案1:移除@Schema中的format属性
Springdoc会自动根据LocalDateTime类型推断出date-time格式,手动指定format="date-time"会触发框架的默认示例替换逻辑。修改后的代码:
import io.swagger.v3.oas.annotations.media.Schema; import java.time.LocalDateTime; public class YourModel { @Schema(description = "Event date and time", example = "2022-12-31T23:59:59") private LocalDateTime creationDateTime; // Getters and setters }
方案2:使用examples属性替代example(保留format的情况)
如果需要显式指定format,使用examples复数属性配置示例值,该属性不会被默认示例覆盖:
import io.swagger.v3.oas.annotations.media.ExampleObject; import io.swagger.v3.oas.annotations.media.Schema; import java.time.LocalDateTime; public class YourModel { @Schema(description = "Event date and time", format = "date-time", examples = @ExampleObject(value = "2022-12-31T23:59:59")) private LocalDateTime creationDateTime; // Getters and setters }
方案3:全局禁用默认示例替换
通过配置文件关闭Springdoc自动替换日期时间默认示例的行为,适用于需要统一控制所有字段示例的场景:
application.yml
springdoc: model: replace-default-vars-with-examples: false
application.properties
springdoc.model.replace-default-vars-with-examples=false
原因说明
Springdoc 2.x版本中,当字段类型为日期时间且显式指定format="date-time"时,框架会优先使用内置的$date-time作为示例值,从而覆盖@Schema中单个example属性的配置。通过上述三种方式可以规避这一逻辑,让自定义示例正常显示。
内容的提问来源于stack exchange,提问作者Clancinio
相关产品推荐
相关产品推荐

