在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自動化生成的主要場景,可根據項目技術棧選擇合適的方案。