專案已托管於 GitHub:y0ngb1n/spring-boot-samples,歡迎 Star, Fork 😘
Swagger 又稱絲襪哥,號稱可以讓程式設計師邊寫程式邊產生介面文件。
添加 Swagger 2 依賴#
在 pom.xml
中添加 Swagger 2 所需依賴:
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger2</artifactId>
<version>2.9.2</version>
</dependency>
添加 Swagger 的 Java 配置#
@Configuration
@EnableSwagger2
public class SwaggerConfig {
@Bean
public Docket api() {
return new Docket(DocumentationType.SWAGGER_2)
.apiInfo(apiInfo())
.select()
.apis(RequestHandlerSelectors.any())
.paths(PathSelectors.any())
.build();
}
}
Swagger 註解說明#
Swagger 透過註解表明該介面會生成文件,包括介面名、請求方法、參數、返回信息等等。
@Api
:修飾整個類,描述 Controller 的作用@ApiOperation
:描述一個類的某個方法,或者說一個介面@ApiParam
:單個參數描述@ApiModel
:用對象來接收參數@ApiProperty
:用對象接收參數時,描述對象的某個字段@ApiResponse
:HTTP 回應其中 1 個描述@ApiResponses
:HTTP 回應整體描述@ApiIgnore
:使用該註解忽略這個 API@ApiImplicitParam
:一個請求參數@ApiImplicitParams
:多個請求參數
以上這些就是最常用的幾個註解了。
具體其他的註解,查看:https://github.com/swagger-api/swagger-core/wiki/Annotations
更多請參考 Swagger 註解文件
添加 Controller、Model 來測試效果#
@Api(value = "用戶管理", description = "用戶信息的「增、刪、查、改」操作")
@RestController
@RequestMapping(path = "/sample/users")
public class UserController {
private static Map<Long, UserModel> users = Collections.synchronizedMap(new HashMap<>());
@ApiOperation(value = "用戶列表")
@GetMapping(path = "/")
public List<UserModel> getUserList() {
return new ArrayList<>(users.values());
}
@ApiOperation(value = "創建用戶", notes = "根據 User 對象創建用戶")
@ApiImplicitParam(name = "user", value = "用戶詳細實體", required = true, dataTypeClass = UserModel.class)
@PostMapping(path = "/")
public UserModel createUser(@RequestBody UserModel user) {
users.put(user.getId(), user);
return user;
}
@ApiOperation(value = "用戶詳細信息", notes = "根據 ID 獲取用戶詳細信息")
@ApiImplicitParam(name = "id", value = "用戶 ID", required = true, dataType = "Long")
@GetMapping(path = "/{id}")
public UserModel getUser(@PathVariable Long id) {
return users.get(id);
}
@ApiOperation(value = "更新用戶詳細信息", notes = "根據 ID 指定更新對象, 並根據 User 信息來更新用戶詳細信息")
@ApiImplicitParams({
@ApiImplicitParam(name = "id", value = "用戶 ID", required = true, dataTypeClass = Long.class),
@ApiImplicitParam(name = "user", value = "用戶詳細實體", required = true, dataTypeClass = UserModel.class)
})
@PutMapping(path = "/{id}")
public UserModel updateUser(@PathVariable Long id, @RequestBody UserModel user) {
UserModel updateUser = users.get(id);
updateUser.setName(user.getName());
updateUser.setAge(user.getAge());
updateUser.setEmail(user.getEmail());
users.put(id, updateUser);
return updateUser;
}
@ApiOperation(value = "刪除用戶", notes = "根據 ID 指定刪除對象")
@ApiImplicitParam(name = "id", value = "用戶 ID", required = true, dataType = "Long")
@DeleteMapping(path = "/{id}")
public String deleteUser(@PathVariable Long id) {
users.remove(id);
return "success";
}
}
@Data
@ApiModel(value = "用戶模型", description = "用戶詳細信息實體類")
public class UserModel {
@ApiModelProperty(value = "用戶 ID")
private Long id;
@ApiModelProperty(value = "名字", allowableValues = "y0ngb1n, tony")
private String name;
@ApiModelProperty(value = "年齡", allowableValues = "range[1, 120]")
private Integer age;
@ApiModelProperty(value = "郵箱")
private String email;
}
此時可以啟動專案進行驗證是否成功集成 Swagger 2 了,啟動專案後,在日誌中可以看到 Swagger 為我們添加了訪問端點 /v2/api-docs
:
...
2019-12-28 22:19:53.880 INFO 11935 --- [main] pertySourcedRequestMappingHandlerMapping : Mapped URL path [/v2/api-docs] onto method [public org.springframework.http.ResponseEntity<springfox.documentation.spring.web.json.Json> springfox.documentation.swagger2.web.Swagger2Controller.getDocumentation(java.lang.String,javax.servlet.http.HttpServletRequest)]
...
通過瀏覽器訪問 http://localhost:8080/v2/api-docs
,可以發現返回的結果是一段 JSON 串,可讀性非常差。幸運的是 Swagger 2 為我們提供了可視化的交互界面 SwaggerUI,下面我們就一起來試試吧。
添加 Swagger UI 依賴#
同上面一樣,在 pom.xml
中添加 Swagger UI 所需依賴:
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger-ui</artifactId>
<version>2.9.2</version>
</dependency>
添加完成後,重新啟動專案,然後通過瀏覽器訪問 http://localhost:8080/swagger-ui.html
,便可以看到下面的效果:
到這裡就集成 Swagger 成功了,更多高階的操作就等繼續看文件或下面的參考鏈接進一步摸索了,祝學習愉快!
🔗️ 參考鏈接#
- https://www.baeldung.com/swagger-2-documentation-for-spring-rest-api
- https://www.tutorialspoint.com/spring_boot/spring_boot_enabling_swagger2.htm
- http://blog.didispace.com/tags/Swagger/
- https://www.ibm.com/developerworks/cn/java/j-using-swagger-in-a-spring-boot-project/index.html
- https://mp.weixin.qq.com/s/EYnL7T0yOgNXYIrBWBg8hg
- https://github.com/dyc87112/swagger-butler
- https://github.com/SpringForAll/spring-boot-starter-swagger
- https://blog.csdn.net/lilyssh/article/details/82944507