Swagger 為 RESTful API 提供標準化描述、可視化文檔與在線測試界面。Spring Boot 下整合極簡,本文從依賴、配置、分組、註解到權限控制全流程講解。
<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>
@Configuration
@EnableSwagger2
public class SwaggerConfig {
@Bean
public Docket testApi() {
return new Docket(DocumentationType.SWAGGER_2)
.groupName("test") // 分組名,UI 右上角切換
.genericModelSubstitutes(DeferredResult.class)
.useDefaultResponseMessages(false)
.forCodeGeneration(true)
.pathMapping("/")
.select()
.paths(PathSelectors.ant("/api/**")) // 掃描路徑
.build()
.apiInfo(testApiInfo());
}
@Bean
public Docket demoApi() {
return new Docket(DocumentationType.SWAGGER_2)
.groupName("demo")
.forCodeGeneration(false)
.paths(PathSelectors.ant("/demo/**"))
.build()
.apiInfo(demoApiInfo());
}
private ApiInfo testApiInfo() {
return new ApiInfo(
"EHR Platform API",
"EHR Platform's REST API, all applications access object model via JSON.",
"0.1", "NO terms of service",
"dev@company.com",
"Apache License 2.0",
"https://www.apache.org/licenses/LICENSE-2.0.html"
);
}
private ApiInfo demoApiInfo() { ... }
}
啟動後訪問 https://localhost:8080/swagger-ui.html 即可看到分組文檔。
@RestController
@RequestMapping("/api/test")
public class TestController {
@PostMapping("/show")
@ApiOperation(value = "測試接口", notes = "詳細描述")
public String show(
@ApiParam(required = true, name = "name", value = "姓名")
@RequestParam String name) {
return "success";
}
}
@RestController
@RequestMapping("/demo")
public class DemoController {
@PostMapping("/getcount")
@ApiOperation("獲取計數")
public Map<String, Object> getCount() {
return Map.of("count", 158, "msg", "測試");
}
@PostMapping("/jsonTest2")
public Map<String, Object> jsonTest2(@RequestBody Demo demo) { ... }
@PostMapping("/jsonTest6")
public Map<String, Object> jsonTest6(@RequestParam String name, @RequestParam String content) { ... }
@ApiIgnore // 隱藏此 API
@PostMapping("/jsonTest1")
public Map<String, Object> jsonTest1() { ... }
}
| 註解 | 作用位置 | 說明 |
|---|---|---|
@ApiOperation | 方法 | API 簡述、詳細說明、HTTP 方法、響應類型 |
@ApiParam | 參數 | 參數說明、必填、示例值、隱藏 |
@ApiModel / @ApiModelProperty | 類/字段 | DTO/VO 模型文檔 |
@ApiIgnore | 類/方法 | 完全隱藏,不生成文檔 |
@ApiResponse / @ApiResponses | 方法 | 自定義響應碼說明 |
Springfox 2.2.2 未內建 /v2/api-docs 保護,生產環境建議:
/swagger-ui.html、/v2/api-docs/**、/webjars/**。HandlerInterceptor 攔截 /v2/api-docs 驗證 API Key。spring.mvc.static-path-pattern 未覆蓋 /swagger-ui.html,或手動添加 ResourceHandler 映射 classpath:/META-INF/resources/。genericModelSubstitutes 是否包含 ResponseEntity、DeferredResult 等包裝類型。@RequestBody 複雜對象需配合 @ApiModelProperty 顯示字段詳情。