如何从OpenAPI规范仅生成@HttpExchange接口与DTO类?
解决方案
一、调整现有Spring生成器的配置
你可以通过添加额外的configOptions精准控制生成内容,只保留@HttpExchange接口和DTO,同时适配Spring RestClient:
修改后的完整插件配置如下:
<plugin> <groupId>org.openapitools</groupId> <artifactId>openapi-generator-maven-plugin</artifactId> <version>7.2.0</version> <executions> <execution> <goals> <goal>generate</goal> </goals> <configuration> <inputSpec>${project.basedir}/../spec.json</inputSpec> <generatorName>spring</generatorName> <apiPackage>com.my.service.api</apiPackage> <modelPackage>com.my.service.model</modelPackage> <configOptions> <library>spring-http-interface</library> <!-- 适配RestClient而非默认的WebClient --> <useRestClient>true</useRestClient> <!-- 禁用客户端配置、工厂类等多余辅助文件 --> <generateSupportingFiles>false</generateSupportingFiles> <!-- 关闭测试代码生成 --> <generateApiTests>false</generateApiTests> <generateModelTests>false</generateModelTests> <!-- 可选:关闭文档生成以精简输出 --> <generateApiDocumentation>false</generateApiDocumentation> <generateModelDocumentation>false</generateModelDocumentation> </configOptions> </configuration> </execution> </executions> </plugin>
关键配置项说明:
<useRestClient>true</useRestClient>:OpenAPI Generator 7.x版本已原生支持RestClient适配,开启后生成的@HttpExchange接口会兼容RestClient的代理创建逻辑,不再绑定WebClient。<generateSupportingFiles>false</generateSupportingFiles>:彻底关闭辅助文件生成,只保留核心的API接口和DTO模型类,解决你提到的多余配置代码问题。
二、是否需要更换其他生成器?
不需要额外更换生成器,Spring生成器配合上述配置已经完全满足你的需求。目前没有专门仅生成@HttpExchange接口和DTO的独立生成器,Spring生成器是最贴合Spring生态的选择。
三、生成后的使用示例
生成接口和DTO后,你可以自行配置RestClient并创建接口代理:
@Configuration public class RestClientConfig { @Bean public YourApiInterface yourApiInterface() { RestClient restClient = RestClient.builder() .baseUrl("https://your-api-base-url.com") // 自定义授权、代理等配置 .defaultHeader("Authorization", "Bearer " + getAuthToken()) .requestFactory(createProxyEnabledRequestFactory()) .build(); RestClientAdapter adapter = RestClientAdapter.create(restClient); HttpServiceProxyFactory factory = HttpServiceProxyFactory.builderFor(adapter).build(); return factory.createClient(YourApiInterface.class); } // 自定义授权逻辑 private String getAuthToken() { // 实现你的token获取逻辑 return "your-token"; } // 自定义代理配置 private ClientHttpRequestFactory createProxyEnabledRequestFactory() { // 实现你的代理客户端逻辑 return new HttpComponentsClientHttpRequestFactory(); } }
这样就能完全由你掌控RestClient的配置细节,同时复用生成的API接口和DTO。
内容的提问来源于stack exchange,提问作者ch4mp
相关产品推荐
相关产品推荐

