Spring Boot 項目集成 Swagger 配置及使用指南
一、Swagger 簡介
Swagger 是一個用于設計、構建、文檔化和使用 RESTful API 的框架。通過集成 Swagger,開發者可以:
- 自動生成實時 API 文檔
- 直接在瀏覽器中測試 API 接口
- 減少手動編寫文檔的工作量
- 支持團隊協作開發
二、環境配置(Spring Boot 2.7.x 示例)
1. 添加 Maven 依賴
<!-- pom.xml -->
<dependency><groupId>io.springfox</groupId><artifactId>springfox-swagger2</artifactId><version>3.0.0</version>
</dependency>
<dependency><groupId>io.springfox</groupId><artifactId>springfox-swagger-ui</artifactId><version>3.0.0</version>
</dependency>
2. 創建配置類
@Configuration
@EnableSwagger2
public class SwaggerConfig {@Beanpublic Docket api() {return new Docket(DocumentationType.SWAGGER_2).select().apis(RequestHandlerSelectors.basePackage("com.example.controller")) // 指定掃描包.paths(PathSelectors.any()).build().apiInfo(apiInfo());}private ApiInfo apiInfo() {return new ApiInfoBuilder().title("API 文檔").description("Spring Boot 集成 Swagger 示例").version("1.0.0").contact(new Contact("開發者", "https://example.com", "contact@example.com")).build();}
}
3. 解決常見啟動問題
# application.yml
spring:mvc:pathmatch:matching-strategy: ANT_PATH_MATCHER # 解決 Spring Boot 2.6+ 版本問題
三、Swagger 注解使用
1. Controller 層注解
@RestController
@Api(tags = "用戶管理接口")
@RequestMapping("/api/users")
public class UserController {@ApiOperation(value = "獲取用戶詳情", notes = "根據ID查詢用戶信息")@GetMapping("/{id}")public ResponseEntity<User> getUser(@ApiParam(value = "用戶ID", required = true, example = "1") @PathVariable Long id) {// 業務邏輯}
}
2. Model 層注解
@ApiModel(description = "用戶實體")
public class User {@ApiModelProperty(value = "用戶ID", example = "1001")private Long id;@ApiModelProperty(value = "用戶名", required = true, example = "john_doe")private String username;// getters/setters
}
四、訪問與測試
1. 訪問文檔頁面
啟動項目后訪問:
http://localhost:8080/swagger-ui/index.html
2. 接口測試示例
- 在 Swagger UI 中找到目標接口
- 點擊 “Try it out”
- 輸入請求參數
- 點擊 “Execute” 發送請求
- 查看響應結果和狀態碼
五、高級配置(可選)
1. 安全配置
// 允許訪問 Swagger 資源
@Configuration
public class WebConfig implements WebMvcConfigurer {@Overridepublic void addResourceHandlers(ResourceHandlerRegistry registry) {registry.addResourceHandler("/swagger-ui/**").addResourceLocations("classpath:/META-INF/resources/webjars/springfox-swagger-ui/");}
}
2. 分組配置
// 創建多個 API 分組
@Bean
public Docket adminApi() {return new Docket(DocumentationType.SWAGGER_2).groupName("管理端接口").select().apis(RequestHandlerSelectors.basePackage("com.example.admin")).build();
}
六、最佳實踐建議
- 在開發環境開啟 Swagger,生產環境建議關閉
- 使用 @ApiIgnore 忽略不需要展示的接口
- 保持文檔與代碼同步更新
- 為每個參數添加示例值(example)
- 合理使用響應狀態碼描述
七、常見問題解決
- 頁面404:檢查依賴版本是否沖突
- 接口未顯示:確認包掃描路徑正確
- 參數類型錯誤:添加 @RequestParam/@PathVariable 注解
- 日期格式問題:在配置中添加全局日期格式
通過以上配置和使用方法,開發者可以快速在 Spring Boot 項目中集成 Swagger,顯著提升 API 開發效率。建議結合實際項目需求靈活運用各種注解,并定期查看生成的文檔驗證準確性。