1作者: barissayli9 个月前
许多后端团队会将 API 响应封装在一个通用的信封中(状态、消息、错误、数据)。 然而,OpenAPI Generator 本身并不支持泛型——它通常为每个端点生成一个包装类,从而重复数十次相同的字段。 我构建了一个演示 Spring Boot 3.4 微服务 + OpenAPI 3.1 项目,展示了如何通过以下方式解决这个问题: * 一个小的 Springdoc OpenApiCustomizer,使用供应商扩展标记包装器模式 * 一个微小的 Mustache 模板覆盖,生成扩展可重用泛型基类的精简 shell * 完整的 CRUD 示例(创建、获取、更新、删除),带有类型安全的客户端代码 * 使用 MockWebServer 的集成测试 * HttpClient5 支持连接池和超时 结果:生成器不再生成数十个重复的包装器,而是发出一个可重用的 `ServiceClientResponse<T>` 基类 + 精简的特定于端点的 shell。客户端代码保持简洁、类型安全,并且更易于维护。 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 社区的反馈