SpringBoot中如何在Swagger OpenApi文档覆盖RequestBody的示例与Schema?
自定义Springdoc OpenAPI 3.0文档:解决RequestBody为String时的Schema/Example显示问题
问题背景
我使用Spring Boot 3.2.2开发REST API,需要完全自定义Swagger OpenAPI 3.0文档。由于API需求限制,控制器方法的@RequestBody只能接收String类型(无法直接使用后续JSON映射的DTO类),但希望在Swagger文档中展示该DTO的「Example Value」和「Schema」。
当前代码
控制器代码
public ResponseEntity<Object> createSaveObjects(@RequestBody String json) {...}
Springdoc配置类代码
@OpenAPIDefinition @Configuration public class SpringdocConfig { @Bean OpenAPI baseOpenAPI() { OpenAPI openAPI = new OpenAPI(); // Info Info info = new Info() .title("Documentation") .description("blubb") .version("1.0.0"); openAPI.setInfo(info); // Paths Paths paths = new Paths(); paths.addPathItem("/object", new PathItem() .post(new Operation() .summary("saves objects") .description("saves objects") .requestBody(new RequestBody() .description("blubb") .required(true) .content(new Content() .addMediaType("application/json", new io.swagger.v3.oas.models.media.MediaType() .schema(new Schema() .type("object") .addProperty("Name", new Schema().type("string").example("string")) .addProperty("Origin", new Schema().type("int").example(4)) )...
效果对比
期望效果
Request body application/json blibb Example Value { "Name": "string", "Origin": 4 }
实际效果
Request body application/json blibb Example Value "string"
解决方案
问题根源是Springdoc会优先解析控制器方法中@RequestBody String json的String类型,覆盖了配置类中自定义的Schema。以下两种方法可以解决:
方法一:通过@Schema注解直接修改控制器参数
在控制器的String参数上添加@Schema注解,强制指定对应的Schema和示例,覆盖默认的String类型映射:
import io.swagger.v3.oas.annotations.media.Schema; public ResponseEntity<Object> createSaveObjects( @RequestBody @Schema( type = "object", example = "{\"Name\": \"string\", \"Origin\": 4}", properties = { @Schema(name = "Name", type = "string", example = "string"), @Schema(name = "Origin", type = "integer", example = "4") } ) String json ) {...}
方法二:在配置类中完善自定义配置
如果不想修改控制器代码,可在SpringdocConfig中为请求体的MediaType直接设置完整的示例JSON字符串,同时确保Schema定义正确:
@OpenAPIDefinition @Configuration public class SpringdocConfig { @Bean OpenAPI baseOpenAPI() { // 定义DTO的Schema结构 Schema dtoSchema = new Schema() .type("object") .addProperty("Name", new Schema().type("string").example("string")) .addProperty("Origin", new Schema().type("integer").example(4)); // 定义完整的示例JSON String requestExample = "{\"Name\": \"string\", \"Origin\": 4}"; OpenAPI openAPI = new OpenAPI() .info(new Info() .title("Documentation") .description("blubb") .version("1.0.0")) .paths(new Paths() .addPathItem("/object", new PathItem() .post(new Operation() .summary("saves objects") .description("saves objects") .requestBody(new RequestBody() .description("blubb") .required(true) .content(new Content() .addMediaType("application/json", new io.swagger.v3.oas.models.media.MediaType() .schema(dtoSchema) .example(requestExample) // 直接设置示例JSON ) ) ) ) ); return openAPI; } }
另外,确保使用与Spring Boot 3.2.2兼容的Springdoc版本,推荐springdoc-openapi-starter-webmvc-ui:2.2.0及以上。
内容的提问来源于stack exchange,提问作者paula
相关产品推荐
相关产品推荐

