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

如何通过OpenAPI Generator生成接收完整HttpHeaders的Spring Boot控制器

如何通过OpenAPI Generator生成带完整HttpHeaders参数的Spring Boot控制器

可以实现,通过OpenAPI Generator的Spring扩展参数即可配置生成接收HttpHeaders对象的控制器方法,具体步骤如下:

1. 在OpenAPI YAML中配置特殊Header参数

在你的OpenAPI定义文件中,添加一个in: header的参数,通过x-spring-header-type扩展指定参数类型为Spring的HttpHeaders:

openapi: 3.0.3
info:
  title: Dummy API
  version: 1.0.0
paths:
  /dummyUrl:
    post:
      summary: 处理请求并接收完整Header
      requestBody:
        required: true
        content:
          application/json:
            schema:
              $ref: '#/components/schemas/UserDefineObject'
      parameters:
        - name: headers
          in: header
          required: false # 根据业务需求调整是否必填
          schema:
            type: object # 声明为object类型,配合扩展参数指定实际类型
          x-spring-header-type: org.springframework.http.HttpHeaders # 关键扩展参数
      responses:
        '200':
          description: 成功响应
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/DummyResponse'
components:
  schemas:
    UserDefineObject:
      type: object
      properties:
        id:
          type: integer
        name:
          type: string
    DummyResponse:
      type: object
      properties:
        status:
          type: string
        data:
          type: string

2. 配置OpenAPI Generator生成Spring代码

确保使用支持Spring扩展的生成器(如spring或spring-boot),以下是Maven插件的示例配置:

<plugin>
  <groupId>org.openapitools</groupId>
  <artifactId>openapi-generator-maven-plugin</artifactId>
  <version>6.6.0</version> <!-- 使用较新版本以支持扩展参数 -->
  <executions>
    <execution>
      <goals>
        <goal>generate</goal>
      </goals>
      <configuration>
        <inputSpec>${project.basedir}/src/main/resources/openapi.yaml</inputSpec>
        <generatorName>spring</generatorName>
        <configOptions>
          <interfaceOnly>true</interfaceOnly> <!-- 可选:仅生成控制器接口 -->
          <java8>true</java8>
          <useSpringBoot3>true</useSpringBoot3> <!-- 根据你的Spring Boot版本调整 -->
        </configOptions>
      </configuration>
    </execution>
  </executions>
</plugin>

3. 生成后的控制器代码效果

生成的控制器接口会自动生成带@RequestHeader HttpHeaders headers的方法,与你提供的示例代码一致:

@PostMapping(value = "/dummyUrl",
             produces = {MediaType.APPLICATION_JSON_VALUE},
             consumes = {MediaType.APPLICATION_JSON_VALUE})
ResponseEntity<DummyResponse> processRequest(@RequestHeader HttpHeaders headers, @RequestBody UserDefineObject userDefineObject);

注意事项

  • 确保OpenAPI Generator版本不低于6.0.0,旧版本可能不支持x-spring-header-type扩展参数
  • required字段可根据业务需求设置为true或false,控制Header参数是否必填
  • 如果使用Gradle插件,配置逻辑与Maven一致,只需调整插件声明方式

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.16 10:27:22