如何用openapi-generator/swagger-codegen-maven-plugin生成纯Kotlin Spring客户端代码
生成纯Kotlin的Spring可自动注入客户端(RestTemplate/Feign风格)
以下是使用openapi-generator-maven-plugin生成纯Kotlin、支持Spring自动注入的客户端方案,无需混用Java代码:
一、RestTemplate风格自动注入客户端
1. Maven插件配置
指定kotlin语言和spring库,开启Spring组件注解与RestTemplate支持:
<plugin> <groupId>org.openapitools</groupId> <artifactId>openapi-generator-maven-plugin</artifactId> <version>6.6.0</version> <executions> <execution> <id>kotlin-rest-client</id> <goals> <goal>generate</goal> </goals> <configuration> <inputSpec>${project.basedir}/src/main/resources/openapi.yaml</inputSpec> <generatorName>kotlin</generatorName> <library>spring</library> <output>${project.build.directory}/generated-sources/openapi-rest</output> <apiPackage>com.yourteam.api.client</apiPackage> <modelPackage>com.yourteam.api.model</modelPackage> <configOptions> <component>true</component> <restTemplate>true</restTemplate> <kotlinNullable>true</kotlinNullable> <useSpringBoot3>true</useSpringBoot3> </configOptions> </configuration> </execution> </executions> </plugin>
2. 直接使用
生成的客户端类自带@Component注解,可直接通过@Autowired注入:
@Service class OrderService { @Autowired private lateinit var productApiClient: ProductApiClient fun getProductDetail(id: Long): Product { return productApiClient.getProductById(id) } }
二、Feign风格自动注入客户端
1. Maven插件配置
指定feign库,启用Spring Cloud Feign支持:
<plugin> <groupId>org.openapitools</groupId> <artifactId>openapi-generator-maven-plugin</artifactId> <version>6.6.0</version> <executions> <execution> <id>kotlin-feign-client</id> <goals> <goal>generate</goal> </goals> <configuration> <inputSpec>${project.basedir}/src/main/resources/openapi.yaml</inputSpec> <generatorName>kotlin</generatorName> <library>feign</library> <output>${project.build.directory}/generated-sources/openapi-feign</output> <apiPackage>com.yourteam.feign.client</apiPackage> <modelPackage>com.yourteam.feign.model</modelPackage> <configOptions> <useSpringCloudFeign>true</useSpringCloudFeign> <component>true</component> <kotlinNullable>true</kotlinNullable> <springBoot3>true</springBoot3> </configOptions> </configuration> </execution> </executions> </plugin>
2. 补充依赖与配置
添加Spring Cloud Feign依赖:
<dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-openfeign</artifactId> </dependency>
在Spring启动类上开启Feign扫描:
@SpringBootApplication @EnableFeignClients(basePackages = ["com.yourteam.feign.client"]) class Application
3. 直接使用
生成的Feign接口自带@FeignClient注解,直接注入调用:
@Service class PaymentService { @Autowired private lateinit var paymentFeignClient: PaymentFeignApi fun createPayment(orderId: Long): PaymentResult { return paymentFeignClient.initPayment(orderId) } }
注意事项
- 确保OpenAPI Spec为3.x版本,openapi-generator对其兼容性更好
- 插件版本优先选择最新稳定版,避免Kotlin语法兼容问题
- 若需自定义RestTemplate/Feign配置,直接在Spring容器中声明对应Bean即可,生成的客户端会自动复用
内容的提问来源于stack exchange,提问作者drugzverya
相关产品推荐
相关产品推荐

