# SpringBoot項目接口之Swagger怎么用
## 一、Swagger簡介與核心價值
### 1.1 什么是Swagger
Swagger是一套圍繞OpenAPI規范構建的開源工具鏈,主要用于:
- **API文檔自動化生成**:根據代碼注釋實時生成交互式文檔
- **接口調試**:直接在瀏覽器中測試API接口
- **客戶端SDK生成**:支持多種語言的客戶端代碼生成
版本演進:
- Swagger 1.0 → Swagger 2.0 → OpenAPI 3.0
- 目前主流實現為Springfox Swagger(2.x)和SpringDoc OpenAPI(3.0+)
### 1.2 為什么選擇Swagger
對比傳統文檔工具的優勢:
```diff
+ 實時同步:代碼變更立即反映到文檔
+ 交互體驗:內置API測試功能
+ 標準化:遵循OpenAPI規范
- 手動維護的文檔容易過時
- 需要額外使用Postman等測試工具
Maven依賴配置:
<!-- Springfox Swagger2 核心庫 -->
<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>
啟動類配置:
@SpringBootApplication
@EnableSwagger2 // 啟用Swagger
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}
@Configuration
public class SwaggerConfig {
@Bean
public 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("包含用戶、訂單、商品模塊")
.version("1.0")
.contact(new Contact("DevTeam", "https://example.com", "dev@example.com"))
.build();
}
}
| 注解 | 作用域 | 說明 |
|---|---|---|
@Api |
類 | 標記控制器類功能描述 |
@ApiOperation |
方法 | 接口方法說明(可配置響應碼) |
@ApiParam |
參數 | 單個參數說明(非RequestBody時使用) |
示例代碼:
@Api(tags = "用戶管理模塊")
@RestController
@RequestMapping("/user")
public class UserController {
@ApiOperation(value = "創建用戶", notes = "需要提供用戶名和密碼")
@PostMapping
public Result<User> createUser(
@ApiParam(value = "用戶DTO", required = true)
@RequestBody UserDTO dto) {
// 實現邏輯
}
}
@ApiModel(description = "用戶實體")
public class User {
@ApiModelProperty(value = "用戶ID", example = "1001")
private Long id;
@ApiModelProperty(value = "用戶名", required = true, example = "admin")
private String username;
// getters/setters
}
@ApiImplicitParams:描述非實體類參數@ApiResponse:自定義HTTP響應碼說明@ApiIgnore:排除特定參數或方法http://localhost:8080/swagger-ui.htmlPOST /user){
"username": "test123",
"password": "123456"
}
// 僅允許認證用戶訪問Swagger
@Bean
public SecurityConfiguration security() {
return SecurityConfigurationBuilder.builder()
.enableCsrfSupport(true)
.build();
}
// 后臺管理API分組
@Bean
public Docket adminApi() {
return new Docket(DocumentationType.SWAGGER_2)
.groupName("后臺管理")
.select()
.paths(PathSelectors.ant("/admin/**"))
.build();
}
// 移動端API分組
@Bean
public Docket mobileApi() {
// 類似配置...
}
// 添加JWT認證頭參數
private List<Parameter> globalParameters() {
ParameterBuilder builder = new ParameterBuilder();
return Collections.singletonList(
builder.name("Authorization")
.description("JWT令牌")
.modelRef(new ModelRef("string"))
.parameterType("header")
.required(false)
.build());
}
// 全局響應消息模板
private List<ResponseMessage> responseMessages() {
return Arrays.asList(
new ResponseMessageBuilder()
.code(500)
.message("服務器內部錯誤")
.build(),
new ResponseMessageBuilder()
.code(403)
.message("資源不可用")
.build()
);
}
問題現象: - SpringBoot 2.6+與Swagger 2.9.2路徑匹配沖突
解決方案:
# application.properties
spring.mvc.pathmatch.matching-strategy=ant_path_matcher
@ApiModelProperty(dataType = "string", allowableValues = "A,B,C")
private StatusEnum status;
@ApiOperation("上傳頭像")
@PostMapping(value = "/avatar", consumes = "multipart/form-data")
public Result uploadAvatar(
@ApiParam(value = "頭像文件", required = true)
@RequestPart MultipartFile file) {
// 實現邏輯
}
<!-- 替換為SpringDoc -->
<dependency>
<groupId>org.springdoc</groupId>
<artifactId>springdoc-openapi-ui</artifactId>
<version>1.6.8</version>
</dependency>
@Configuration
@OpenAPIDefinition(
info = @Info(title = "新API文檔")
)
public class OpenApiConfig {
// 無需@Enable注解
}
文檔規范:
@ApiOperation@ApiModel說明版本控制:
.paths(PathSelectors.regex("/v1/.*")) // 只顯示v1接口
生產環境策略:
@Profile({"dev", "test"})
@Configuration
public class SwaggerConfig { ... }
Swagger作為API文檔工具,能顯著提升前后端協作效率。建議: 1. 開發階段:充分利用實時文檔和測試功能 2. 聯調階段:用Swagger UI作為唯一接口規范 3. 發布階段:導出OpenAPI規范文件歸檔
最終效果參考:
圖:標準的Swagger UI界面展示 “`
注:本文實際約3200字(含代碼),如需調整字數可增減以下內容: - 增加更多實戰示例(+300字) - 添加Knife4j等增強工具介紹(+200字) - 擴展OpenAPI 3.0的詳細對比(+400字)
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。