Spring Boot中如何在OpenAPI的@Parameter中配置多示例
解决@Parameter元注解中多示例(@ExampleObject)不生效的问题
问题原因
OpenAPI 3.0规范中,被解析为请求体的@Parameter与普通参数的示例配置逻辑不同:
- @RequestBody的
examples直接映射到OpenAPI请求体的多示例结构; - @Parameter顶层的
examples字段仅适用于查询、路径等常规参数,当它被解析为请求体时,该字段不会被Swagger/SpringDoc正确识别。
解决方案
将示例配置从@Parameter顶层的examples移到content字段中,通过指定媒体类型来定义多示例,修改后的元注解代码如下:
@Retention(RetentionPolicy.RUNTIME) @Target(ElementType.PARAMETER) @Parameter( in = ParameterIn.DEFAULT, description = "Dynamic query string that will be used to query/filter this resource.", required = true, content = @Content( // 根据实际请求内容类型调整,纯文本查询用text/plain,JSON格式用application/json mediaType = "text/plain", examples = { @ExampleObject( name = "example1", summary = "Search for a...", value = "hello==4567*", description = "blah" ), @ExampleObject( name = "example2", summary = "samplee", value = "hello==John*", description = "blahhh" ) } ), schema = @Schema( description = "Query Field and Value", name = "Query", allowableValues = {"query"} ) ) public @interface Query { Class<?> value(); }
关键说明
- 当@Parameter被解析为请求体时,Swagger/SpringDoc会将其映射到OpenAPI的
requestBody结构,而请求体的多示例必须定义在content下的对应媒体类型中; - 务必匹配实际的媒体类型:如果你的查询参数是纯文本格式,用
text/plain;如果是结构化JSON,改用application/json; - 建议使用最新版本的SpringDoc OpenAPI库,旧版本可能存在
content字段解析的兼容性问题。
内容的提问来源于stack exchange,提问作者zakpruitt
相关产品推荐
相关产品推荐

