openapi-generator-maven-plugin生成时如何排除openapi.yaml指定端点
问题场景
当前使用openapi-generator-maven-plugin可基于openapi.yaml正常生成Spring Boot Controller接口,整体功能运行正常。现需要用自定义编写的接口覆盖其中一个自动生成的接口,需要在代码生成阶段排除指定端点。
示例OpenAPI配置片段如下:
paths: /currencies: get: tags: - DomainData summary: Lists all valid currencies available. operationId: "getCurrencies" parameters: - $ref: '#/components/parameters/AcceptLanguage' responses: "200": description: "OK" content: application/json: schema: type: string additionalProperties: type: string '401': $ref: '#/components/responses/Unauthorized' '5XX': $ref: '#/components/responses/Unexpected' /languages: get: tags: - DomainData summary: Lists all valid languages available. operationId: "getLanguages" parameters: - $ref: '#/components/parameters/AcceptLanguage' responses: "200": description: "OK" content: application/json: schema: type: string additionalProperties: type: string '401': $ref: '#/components/responses/Unauthorized' '5XX': $ref: '#/components/responses/Unexpected'
需求为生成代码时跳过/languages路径对应的接口生成,其余所有接口保持正常生成。
实现方案
不需要修改原始openapi.yaml文件,直接在maven插件配置中通过openapiNormalizer规则配置路径排除即可,配置要点如下:
- 在插件配置的
configOptions同级添加openapiNormalizer节点,使用对应规则指定要排除的路径/端点 - 多个排除目标用英文逗号分隔即可
完整插件配置示例:
<plugin> <groupId>org.openapitools</groupId> <artifactId>openapi-generator-maven-plugin</artifactId> <version>6.6.0</version> <!-- 替换为实际使用的版本,5.x及以上版本均支持该规则 --> <executions> <execution> <goals> <goal>generate</goal> </goals> <configuration> <inputSpec>${project.basedir}/src/main/resources/openapi.yaml</inputSpec> <generatorName>spring</generatorName> <apiPackage>com.example.demo.api</apiPackage> <modelPackage>com.example.demo.model</modelPackage> <!-- 核心配置:排除指定路径 --> <openapiNormalizer> <rules> <!-- 排除整个/languages路径下的所有接口 --> <EXCLUDE_PATHS>/languages</EXCLUDE_PATHS> <!-- 如果仅需排除路径下的指定HTTP方法,换成EXCLUDE_OPERATIONS规则即可,格式为HTTP方法:路径,例如排除GET /languages就写get:/languages --> </rules> </openapiNormalizer> <configOptions> <interfaceOnly>true</interfaceOnly> <!-- 原有其余配置保持不变 --> </configOptions> </configuration> </execution> </executions> </plugin>
配置说明:如果需要排除多个端点,直接在规则值中用英文逗号分隔即可,例如
EXCLUDE_OPERATIONS的值写get:/languages,post:/test就会同时排除GET类型的/languages接口和POST类型的/test接口。
配置完成后重新执行maven代码生成命令,指定排除的接口就不会出现在自动生成的API/Controller文件中,后续编写自定义同名接口不会出现路由、类方法冲突问题。
内容的提问来源于stack exchange,提问作者shortQuestion
相关产品推荐
相关产品推荐

