微服務架構下,RESTful API 往往服務於多端(iOS、Android、Web),接口文檔維護成本高、易與代碼脫節。Swagger 2 通過**代碼即文檔**理念,完美解決此痛點。本文詳細演示 Spring Boot 整合 Swagger 2 全流程,含依賴、配置、注解豐富文檔、UI 調試實戰。
@ApiOperation、@ApiImplicitParam 等)細化接口描述<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger2</artifactId>
<version>2.9.2</version> <!-- 建議用 2.9.x 穩定版 -->
</dependency>
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger-ui</artifactId>
<version>2.9.2</version>
</dependency>
@Configuration
@EnableSwagger2
public class Swagger2Config {
@Bean
public Docket createRestApi() {
return new Docket(DocumentationType.SWAGGER_2)
.apiInfo(apiInfo())
.select()
.apis(RequestHandlerSelectors.basePackage("com.didispace.web")) // 掃描 Controller 包
.paths(PathSelectors.any())
.build();
}
private ApiInfo apiInfo() {
return new ApiInfoBuilder()
.title("Spring Boot RESTful APIs 文檔")
.description("更多技術分享:https://blog.didispace.com/")
.termsOfServiceUrl("https://blog.didispace.com/")
.contact(new Contact("程序猿DD", "https://blog.didispace.com/", "dd@didispace.com"))
.version("1.0")
.build();
}
}
關鍵點:@EnableSwagger2 啟用自動配置;Docket 定義文檔生成策略;basePackage 限定掃描範圍,避免掃描無關類。
@RestController
@RequestMapping("/users")
@Api(tags = "用戶管理接口") // 控制器級標籤
public class UserController {
private static final Map<Long, User> users = new ConcurrentHashMap<>();
@GetMapping
@ApiOperation(value = "獲取用戶列表", notes = "返回所有用戶信息")
public List<User> getUserList() {
return new ArrayList<>(users.values());
}
@PostMapping
@ApiOperation(value = "創建用戶", notes = "根據 User 對象創建用戶")
@ApiImplicitParam(name = "user", value = "用戶詳細實體", required = true, dataTypeClass = User.class)
public String postUser(@RequestBody User user) {
users.put(user.getId(), user);
return "success";
}
@GetMapping("/{id}")
@ApiOperation(value = "獲取用戶詳情", notes = "根據 URL id 獲取用戶詳細信息")
@ApiImplicitParam(name = "id", value = "用戶 ID", required = true, dataTypeClass = Long.class, paramType = "path")
public User getUser(@PathVariable Long id) {
return users.get(id);
}
@PutMapping("/{id}")
@ApiOperation(value = "更新用戶", notes = "根據 id 更新用戶信息")
@ApiImplicitParams({
@ApiImplicitParam(name = "id", value = "用戶 ID", required = true, dataTypeClass = Long.class, paramType = "path"),
@ApiImplicitParam(name = "user", value = "用戶詳細實體", required = true, dataTypeClass = User.class)
})
public String putUser(@PathVariable Long id, @RequestBody User user) {
User u = users.get(id);
if (u != null) {
u.setName(user.getName());
u.setAge(user.getAge());
users.put(id, u);
}
return "success";
}
@DeleteMapping("/{id}")
@ApiOperation(value = "刪除用戶", notes = "根據 id 刪除用戶")
@ApiImplicitParam(name = "id", value = "用戶 ID", required = true, dataTypeClass = Long.class, paramType = "path")
public String deleteUser(@PathVariable Long id) {
users.remove(id);
return "success";
}
}
https://localhost:8080/swagger-ui.htmlTry it out → 填寫參數(Body 參數點擊 Model Schema 自動生成模板)→ Execute → 查看實際請求/響應/HTTP 狀態碼| 注解 | 作用位置 | 說明 |
|---|---|---|
@Api | Controller 類 | 接口分組標題、描述 |
@ApiOperation | 方法 | 單個接口標題、詳細說明 |
@ApiImplicitParams / @ApiImplicitParam | 方法 | 參數詳細描述:name、value、required、dataTypeClass、paramType(path/query/body/header/form) |
@ApiModel / @ApiModelProperty | 實體類/字段 | 模型/字段描述、示例值、隱藏字段 |
@ApiIgnore | 方法/類/參數 | 隱藏不想暴露的接口/參數 |
@ApiResponse / @ApiResponses | 方法 | 響應碼、消息、模型映射 |
Result<T> 統一返回,配合 @ApiModelProperty 描述 data 字段,或實現 ModelConverter 自定義模型解析。Docket 可創建多個 Bean,配合 groupName 區分 v1/v2 或 模塊。SecurityScheme、SecurityContext,UI 自動顯示 Authorization 輸入框。@Profile({"dev", "test"}) 限制僅開發/測試環境啟用,避免接口信息洩露。springdoc-openapi,原生支持 OpenAPI 3 規範,維護更活躍。Swagger 2 讓「文檔驅動開發」落地:接口定義即文檔生成,前後端並行開發零溝通成本,測試介入零部署成本。在 Spring Boot 中集成僅需「2 個依賴 + 1 個配置類 + 幾行注解」,ROI 極高。建議團隊建立**接口文檔規範**(必填注解、參數描述標準),並納入 Code Review 檢查項,養成「改代碼同步改注解」肌肉記憶。