首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> Java 程式設計 >> Java 綜合教學

Spring Boot 整合 Swagger 2 自動生成 API 文檔

     編輯:Java 綜合教學

Spring Boot 整合 Swagger 2 自動生成 API 文檔

Swagger 是 RESTful API 文檔生成與測試的標準工具。Spring Boot 整合 Swagger 2 極其簡單,僅需引入依賴、啟用註解、在 Controller 添加文檔註解即可。本文演示完整接入流程與常用註解詳解。

依賴配置

<dependency>
    <groupId>io.springfox</groupId>
    <artifactId>springfox-swagger2</artifactId>
    <version>2.2.2</version>
</dependency>
<dependency>
    <groupId>io.springfox</groupId>
    <artifactId>springfox-swagger-ui</artifactId>
    <version>2.2.2</version>
</dependency>

啟用 Swagger

@SpringBootApplication
@EnableSwagger2
public class Application {
    public static void main(String[] args) {
        SpringApplication.run(Application.class, args);
    }
}

@EnableSwagger2 啟用掃描,掃描范圍由 @ComponentScan 決定(默認主類同包及子包)。

Controller 文檔註解

@RestController
@RequestMapping("/user")
@Api("UserController 相關 API")
public class UserController {
    @Autowired
    private UserService userService;

    @ApiOperation("獲取用戶信息")
    @ApiImplicitParams({
        @ApiImplicitParam(paramType = "header", name = "username", dataType = "String", required = true, value = "用戶姓名", defaultValue = "zhaojigang"),
        @ApiImplicitParam(paramType = "query", name = "password", dataType = "String", required = true, value = "用戶密碼", defaultValue = "wangna")
    })
    @ApiResponses({
        @ApiResponse(code = 400, message = "請求參數錯誤"),
        @ApiResponse(code = 404, message = "路徑不存在")
    })
    @GetMapping("/getUser")
    public User getUser(@RequestHeader("username") String username, @RequestParam("password") String password) {
        return userService.getUser(username, password);
    }
}

核心註解詳解

paramType 對應關係: header→@RequestHeader, query→@RequestParam, path→@PathVariable, body→@RequestBody

測試效果

  1. 啟動應用
  2. 訪問 https://localhost:8080/swagger-ui.html
  3. 界面展示:分組標題(@Api)、HTTP 方法、接口說明(@ApiOperation)、參數表(@ApiImplicitParams)、響應碼(@ApiResponses)
  4. 點擊 Try it out! 實時測試接口,查看響應 JSON

Swagger UI 列表

接口測試響應

優勢總結

  • 前後端並行開發,文檔即代碼,自動同步
  • 內置測試控制台,無需 Postman/curl
  • 支持複雜參數類型、響應模型、分組標籤
  • Spring Boot 整合零配置,幾分鐘上手
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved
註解作用位置關鍵屬性
@Api類value/description:接口分組說明
@ApiOperation方法value:接口說明;notes:詳細描述
@ApiImplicitParams方法包含多個 @ApiImplicitParam
@ApiImplicitParam@ApiImplicitParams 內paramType(header/query/path/body/form)、name、dataType、required、value、defaultValue
@ApiResponses方法包含多個 @ApiResponse
@ApiResponse@ApiResponses 內code、message、response(異常類)