在Linux系统上实现Swagger自动化生成前,需安装以下基础工具:
sudo apt install openjdk-11-jdk)。wget https://repo1.maven.org/maven2/io/swagger/swagger-codegen-cli/3.0.29/swagger-codegen-cli-3.0.29.jar -O swagger-codegen-cli.jar)。使用**OpenAPI Specification(OAS)**定义API结构,常见格式为swagger.yaml(YAML格式更易读)或swagger.json。规范需包含API元数据(标题、版本)、路径(接口URL)、操作(GET/POST等)、参数(请求头/体)、响应(状态码、数据格式)及组件(数据模型)。
示例(swagger.yaml):
openapi: 3.0.0
info:
title: Sample API
version: 1.0.0
paths:
/users:
get:
summary: 获取用户列表
responses:
'200':
description: 成功返回用户数组
content:
application/json:
schema:
type: array
items:
$ref: '#/components/schemas/User'
components:
schemas:
User:
type: object
properties:
id:
type: integer
format: int64
name:
type: string
此文件是自动化生成文档的核心输入。
根据技术栈选择合适的工具,常见方案如下:
适用于Java、Python、JavaScript等多种语言的客户端代码及文档生成。通过命令行调用,将swagger.yaml转换为所需格式:
java -jar swagger-codegen-cli.jar generate \
-i path/to/swagger.yaml \
-l html2 \
-o path/to/output/docs
pom.xml中添加openapi-generator-maven-plugin,实现构建时自动生成:<plugin>
<groupId>org.openapitools</groupId>
<artifactId>openapi-generator-maven-plugin</artifactId>
<version>5.2.1</version>
<executions>
<execution>
<goals>
<goal>generate</goal>
</goals>
<configuration>
<inputSpec>${project.basedir}/src/main/resources/swagger.yaml</inputSpec>
<generatorName>html2</generatorName>
<output>${project.build.directory}/generated-docs</output>
</configuration>
</execution>
</executions>
</plugin>
构建时(mvn clean package),文档会自动生成到指定目录。针对Spring Boot项目,通过注解和配置实现API文档自动生成,无需手动编写swagger.yaml。
pom.xml中引入SpringFox依赖:<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger2</artifactId>
<version>2.9.2</version>
</dependency>
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger-ui</artifactId>
<version>2.9.2</version>
</dependency>
@Configuration
@EnableSwagger2
public class SwaggerConfig {
@Bean
public Docket api() {
return new Docket(DocumentationType.SWAGGER_2)
.select()
.apis(RequestHandlerSelectors.basePackage("com.example.controller")) // 扫描的Controller包
.paths(PathSelectors.any())
.build();
}
}
http://localhost:8080/swagger-ui.html查看交互式文档(端口根据实际调整)。为实现真正的自动化(代码提交后自动生成文档),可将Swagger生成步骤集成到CI/CD管道(如Jenkins、GitLab CI):
mvn generate-sources)。pipeline {
agent any
stages {
stage('Generate Docs') {
steps {
sh 'mvn generate-sources' // 触发SpringFox生成文档
}
}
stage('Deploy Docs') {
steps {
sh 'cp -r target/generated-docs/* /var/www/html/api-docs/' // 部署到Nginx目录
}
}
}
}
通过这种方式,团队每次更新代码后都能获取最新的API文档,确保文档与代码同步。
swagger.yaml中的接口定义与实际代码逻辑一致,避免文档与实现不符。swagger.yaml纳入版本控制系统(如Git),跟踪接口变更历史。以上方法覆盖了Linux环境下Swagger自动化生成的主要场景,可根据项目技术栈选择合适的方案。