Swagger Codegen Maven Plugin 是一个 Maven 插件,它能够根据 Swagger/OpenAPI 规范文件自动生成客户端或服务器端代码。这个插件基于 Swagger Codegen 工具,可以简化 API 开发流程,确保 API 实现与文档保持一致。
<plugin>
<groupId>io.swagger</groupId>
<artifactId>swagger-codegen-maven-plugin</artifactId>
<version>3.0.34</version> <!-- 使用最新版本 -->
<executions>
<execution>
<goals>
<goal>generate</goal>
</goals>
<configuration>
<inputSpec>${project.basedir}/src/main/resources/api.yaml</inputSpec>
<language>spring</language> <!-- 生成Spring Boot代码 -->
<configOptions>
<sourceFolder>src/gen/java/main</sourceFolder>
<dateLibrary>java8</dateLibrary>
<interfaceOnly>true</interfaceOnly>
<useTags>true</useTags>
</configOptions>
</configuration>
</execution>
</executions>
</plugin>
假设有以下简单的 OpenAPI 规范 (api.yaml):
openapi: 3.0.1
info:
title: Sample API
version: 1.0.0
paths:
/users:
get:
tags:
- user
summary: Get all users
responses:
'200':
description: A list of users
content:
application/json:
schema:
type: array
items:
$ref: '#/components/schemas/User'
components:
schemas:
User:
type: object
properties:
id:
type: integer
name:
type: string
插件会生成类似以下的接口:
@javax.annotation.Generated(value = "io.swagger.codegen.v3.generators.java.SpringCodegen", date = "2023-04-01T10:00:00.000Z")
@Validated
public interface UsersApi {
@Operation(summary = "Get all users", description = "", tags={ "user" })
@ApiResponses(value = {
@ApiResponse(responseCode = "200", description = "A list of users", content = @Content(mediaType = "application/json", array = @ArraySchema(schema = @Schema(implementation = User.class)))) })
@RequestMapping(value = "/users",
produces = { "application/json" },
method = RequestMethod.GET)
ResponseEntity<List<User>> usersGet();
}
原因:
解决方案:
原因:
解决方案:
原因:
解决方案: 在 configOptions 中添加:
<interfaceOnly>true</interfaceOnly>
<configOptions>
<java8>true</java8>
<dateLibrary>java8</dateLibrary>
<library>spring-boot</library>
<serializableModel>true</serializableModel>
<skipOverwrite>false</skipOverwrite>
<apiPackage>com.example.api</apiPackage>
<modelPackage>com.example.model</modelPackage>
<invokerPackage>com.example.invoker</invokerPackage>
<groupId>com.example</groupId>
<artifactId>api-client</artifactId>
<artifactVersion>1.0.0</artifactVersion>
</configOptions>
通过合理配置 Swagger Codegen Maven Plugin,可以显著提高 API 开发效率,同时确保代码质量与文档一致性。
没有搜到相关的文章