返回首页
最新
许多后端团队将 API 响应封装在一个通用的信封中(状态、消息、错误、数据)。然而,OpenAPI Generator 并不原生支持泛型——它通常为每个端点生成一个包装类,导致相同的字段重复出现数十次。
我构建了一个演示项目,使用 Spring Boot 3.4 和 OpenAPI 3.1,展示了如何解决这个问题:
- 一个小型的 Springdoc OpenApiCustomizer,用于通过供应商扩展标记包装模式
- 一个微小的 Mustache 模板覆盖,生成扩展可重用泛型基础的薄壳
- 完整的 CRUD 示例(创建、获取、更新、删除),并提供类型安全的客户端代码
- 使用 MockWebServer 的集成测试
- 支持 HttpClient5 的连接池和超时设置
结果是:生成器输出一个可重用的 `ServiceClientResponse<T>` 基类和薄的端点特定壳,而不是数十个重复的包装器。客户端代码保持简洁、类型安全,并且更易于维护。
GitHub 仓库(演示代码):
[https://github.com/bsayli/spring-boot-openapi-generics-clients](https://github.com/bsayli/spring-boot-openapi-generics-clients)
详细文章(Medium 文章):
[https://medium.com/@baris.sayli/type-safe-generic-api-responses-with-spring-boot-3-4-openapi-generator-and-custom-templates-ccd93405fb04](https://medium.com/@baris.sayli/type-safe-generic-api-responses-with-spring-boot-3-4-openapi-generator-and-custom-templates-ccd93405fb04)
期待来自 HN 社区的反馈!