如何修改Springdoc OpenAPI Schema的format字段使其仅显示string?
解决Springdoc OpenAPI中Sortable字段format冗余文本问题
问题背景
使用Spring Boot 2.6.1 + Springdoc OpenAPI 1.7.0时,生成的OpenAPI文档中,Sortable实体的sort字段format值被拼接成了string :: Sorts the records according to the parameter.,需要将其修改为仅显示string。
当前生成的Schema片段
{ "components": { "schemas": { "Sortable": { "type": "object", "properties": { "sort": { "type": "string", "description": "Sorts the records according to the parameter.", "format": "string :: Sorts the records according to the parameter.", "example": "date" } } } } } }
预期的Schema片段
{ "components": { "schemas": { "Sortable": { "type": "object", "properties": { "sort": { "type": "string", "description": "Sorts the records according to the parameter.", "format": "string", "example": "date" } } } } } }
对应的Java实体代码
@Getter @Setter public class Sortable { @Schema(description = "Sorts the records according to the parameter.", example = "date", type = "string") private String sort; }
解决方案
方法1:移除@Schema中的冗余type属性(推荐)
Springdoc会根据Java字段类型自动推断schema的type,无需手动指定type = "string"。移除该属性后,format会自动生成为正确的string:
@Getter @Setter public class Sortable { @Schema(description = "Sorts the records according to the parameter.", example = "date") private String sort; }
方法2:显式指定format属性
如果需要保留type属性,可以在@Schema注解中直接指定format = "string",覆盖自动生成的冗余值:
@Getter @Setter public class Sortable { @Schema(description = "Sorts the records according to the parameter.", example = "date", type = "string", format = "string") private String sort; }
方法3:全局配置处理(多字段通用)
如果多个字段都存在此类format冗余问题,可以通过自定义ModelBuilderPlugin全局处理:
import io.swagger.v3.oas.models.media.Schema; import org.springdoc.core.customizers.ModelBuilderPlugin; import org.springframework.stereotype.Component; @Component public class FormatCleanupPlugin implements ModelBuilderPlugin { @Override public void apply(Schema schema) { if ("string".equals(schema.getType()) && schema.getFormat() != null) { // 清理包含"::"的冗余format文本 if (schema.getFormat().contains("::")) { schema.setFormat("string"); } } } @Override public boolean supports(ModelBuilderPlugin.ModelContext modelContext) { return true; } }
内容的提问来源于stack exchange,提问作者Denis Kisina
相关产品推荐
相关产品推荐

