# SpringBoot中Swagger和Knife4j的使用指南
## 一、API文檔工具概述
在現代Web開發中,良好的API文檔是前后端協作的重要基礎。Swagger作為一套開源的API文檔工具,通過注解的方式自動生成RESTful風格的接口文檔。而Knife4j則是Swagger的增強解決方案,在UI界面和功能上都進行了優化。
### 1.1 Swagger核心組件
- **Swagger Core**:處理注解的核心庫
- **Swagger UI**:可視化文檔界面
- **Swagger Editor**:API設計編輯器
- **Swagger Codegen**:代碼生成工具
### 1.2 Knife4j的特點
- 更美觀的UI界面
- 支持接口調試時的動態參數
- 提供離線文檔導出功能
- 增強的注解支持
## 二、SpringBoot集成Swagger
### 2.1 添加Maven依賴
```xml
<!-- Swagger基礎依賴 -->
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger2</artifactId>
<version>2.9.2</version>
</dependency>
<!-- Swagger UI -->
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger-ui</artifactId>
<version>2.9.2</version>
</dependency>
@Configuration
@EnableSwagger2
public class SwaggerConfig {
@Bean
public Docket createRestApi() {
return new Docket(DocumentationType.SWAGGER_2)
.apiInfo(apiInfo())
.select()
.apis(RequestHandlerSelectors.basePackage("com.example.controller"))
.paths(PathSelectors.any())
.build();
}
private ApiInfo apiInfo() {
return new ApiInfoBuilder()
.title("SpringBoot集成Swagger示例")
.description("API接口文檔")
.version("1.0")
.build();
}
}
| 注解 | 作用 | 示例 |
|---|---|---|
| @Api | 修飾Controller類 | @Api(tags = “用戶管理”) |
| @ApiOperation | 修飾方法 | @ApiOperation(“創建用戶”) |
| @ApiParam | 修飾參數 | @ApiParam(“用戶ID”) Long id |
| @ApiModel | 修飾實體類 | @ApiModel(“用戶實體”) |
| @ApiModelProperty | 修飾字段 | @ApiModelProperty(“用戶名”) |
<dependency>
<groupId>com.github.xiaoymin</groupId>
<artifactId>knife4j-spring-boot-starter</artifactId>
<version>3.0.3</version>
</dependency>
@Configuration
@EnableSwagger2
@EnableKnife4j
public class SwaggerConfig {
@Bean
public Docket createRestApi() {
return new Docket(DocumentationType.SWAGGER_2)
.apiInfo(apiInfo())
.select()
.apis(RequestHandlerSelectors.basePackage("com.example.controller"))
.paths(PathSelectors.any())
.build()
.securitySchemes(securitySchemes())
.securityContexts(securityContexts());
}
private List<ApiKey> securitySchemes() {
return Arrays.asList(
new ApiKey("Authorization", "Authorization", "header"));
}
private List<SecurityContext> securityContexts() {
return Arrays.asList(
SecurityContext.builder()
.securityReferences(defaultAuth())
.forPaths(PathSelectors.regex("/.*"))
.build());
}
}
// 添加JWT認證支持
@Bean
public SecurityScheme apiKey() {
return new ApiKey("token", "token", "header");
}
// 多版本API分組
@Bean
public Docket v1Api() {
return new Docket(DocumentationType.SWAGGER_2)
.groupName("v1.0")
.select()
.apis(input -> {
String methodName = input.getHandlerMethod().getMethod().getName();
return methodName.contains("V1");
})
.build();
}
# application-prod.properties
knife4j.production=true
swagger.enabled=false
確保添加了資源映射(SpringBoot 2.6+需要):
@Configuration
public class WebConfig implements WebMvcConfigurer {
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("doc.html")
.addResourceLocations("classpath:/META-INF/resources/");
}
}
@Bean
public Docket api() {
return new Docket(DocumentationType.SWAGGER_2)
.directModelSubstitute(LocalDate.class, String.class)
.directModelSubstitute(LocalDateTime.class, String.class);
}
@ApiModelProperty(value = "訂單狀態", allowableValues = "CREATED,PD,DELIVERED")
private OrderStatus status;
src/styles/theme.scss// 根據注解動態顯示接口
.apis(RequestHandlerSelectors.withMethodAnnotation(ApiOperation.class))
Knife4jHtmlGenerator generator = new Knife4jHtmlGenerator(
"文檔標題",
"/path/to/save",
docket);
generator.generate();
本文詳細介紹了在SpringBoot項目中: 1. 集成Swagger生成基礎API文檔 2. 使用Knife4j增強文檔功能 3. 實際開發中的配置技巧 4. 常見問題的解決方案
通過合理配置,可以顯著提升團隊協作效率。建議生產環境關閉文檔功能,或添加權限控制。
注意事項: - Swagger 2.x已停止維護,新項目建議使用OpenAPI 3.0 - 敏感接口應當添加
@ApiIgnore注解排除 - 文檔應當與代碼同步更新 “`
該文檔共計約2000字,采用Markdown格式編寫,包含: 1. 多級標題結構 2. 代碼塊示例 3. 表格對比 4. 注意事項提示框 5. 配置示例和注解說明 可根據實際項目需求調整具體配置參數和依賴版本。
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。