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

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();
}

关键说明

  1. 当@Parameter被解析为请求体时,Swagger/SpringDoc会将其映射到OpenAPI的requestBody结构,而请求体的多示例必须定义在content下的对应媒体类型中;
  2. 务必匹配实际的媒体类型:如果你的查询参数是纯文本格式,用text/plain;如果是结构化JSON,改用application/json;
  3. 建议使用最新版本的SpringDoc OpenAPI库,旧版本可能存在content字段解析的兼容性问题。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.23 11:10:05