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

如何为Java Record封装的请求参数配置Swagger3内联OpenAPI文档

问题描述

我有如下Controller:

@RestController
@RequestMapping(value = "/client", produces = APPLICATION_JSON_VALUE)
@Tag(name = "Client")
@RequiredArgsConstructor
@Validated
public class PersonController {
    @Operation(summary = "Get client info")
    @GetMapping
    public PersonInfoResponse getPersonInfo(
            @Valid PersonSearchParameters parameters
    ) {
       // some logic
    }
}

查询参数被封装在PersonSearchParameters这个Java Record中,即使不加@RequestParam注解,Java也会将其识别为查询参数:

@ValidPersonSearchParameter // custom validation
public record PersonSearchParameters(
        @Schema(required = true, description = "Search key")
        @NotNull SearchKey searchKey,

        @Schema(required = true, description = "Value")
        @NotBlank String value,

        @Schema(description = "Birthday")
        @DateTimeFormat(pattern = "yyyy-MM-dd") LocalDate birthday
) {
}

我希望在Swagger中,这些参数的Schema能像JSON请求体一样直接显示在请求区域内,而非仅显示示例值或单独展示Schema。我尝试过为方法添加@Parameters注解、为参数添加@RequestParam("parameters")注解,但并未生效,请问该如何解决?

解决方案

使用SpringDoc提供的@ParameterObject注解即可解决,它专门用于标记封装多查询参数的对象,能让Swagger UI在请求区域内展示完整的Schema结构,同时保留每个字段作为独立查询参数的功能。

1. 给Controller参数添加@ParameterObject

修改Controller方法的参数声明,加上@ParameterObject注解:

@Operation(summary = "Get client info")
@GetMapping
public PersonInfoResponse getPersonInfo(
        @Valid @ParameterObject PersonSearchParameters parameters
) {
   // some logic
}

2. 确认SpringDoc依赖配置

如果项目用的是SpringDoc OpenAPI(取代旧版Swagger2的方案),确保依赖正确引入(以Maven为例):

<dependency>
    <groupId>org.springdoc</groupId>
    <artifactId>springdoc-openapi-starter-webmvc-ui</artifactId>
    <version>2.2.0</version> <!-- 推荐使用最新稳定版本 -->
</dependency>

效果说明

  • 添加@ParameterObject后,Swagger UI会在请求区域展示PersonSearchParameters的完整Schema结构,和JSON请求体的展示形式一致;同时每个字段会作为独立的查询参数选项存在,不影响接口的实际请求逻辑。
  • Record中原有的@Schema、@NotNull等注解都会被正常识别,字段的必填性、描述、格式约束会准确显示在Swagger界面中。
  • 无需再添加@RequestParam或@Parameters注解,避免配置冲突。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.11 23:15:35