【Spring Security OAuth2筆記系列】- 【使用Spring MVC開發RESTful API】 使用swagger自動生成html文檔

使用swagger自動生成html文檔

本節內容

  • 使用swagger自動生成html文檔
  • 使用WireMock快速僞造restful服務

前後分離並行開發的時候(當然不是一個人從前到後都幹那種);那麼提供文檔就很有必要了。

光看文檔不是那麼的直觀。僞造服務可能更直觀(個人感覺而言,文檔詳細,自己在postman這種工具中去調用也是一樣的)

初體驗

添加兩個依賴

// 掃描程序生成文檔數據
// http://springfox.github.io/springfox/docs/current/
// https://mvnrepository.com/artifact/io.springfox/springfox-swagger2
compile group: 'io.springfox', name: 'springfox-swagger2', version: '2.9.2'
// 提供可視化界面
// https://mvnrepository.com/artifact/io.springfox/springfox-swagger-ui
compile group: 'io.springfox', name: 'springfox-swagger-ui', version: '2.9.2'

添加註解開啓swagger

@EnableSwagger2
public class DemoApplication {

啓動程序後,訪問:http://localhost:8080/swagger-ui.html 就能看到一個界面。裏面會顯示該程序中所有的的controller斷點。並掃描該斷點的註解等信息進行分析一些有關斷點的信息;

可以點擊Try it out按鈕發起請求,然後在界面上會把響應結果返回;

這樣看的確挺方便的;

使用註解自定義信息

定義api描述

@ApiOperation(value = "用戶查詢服務")  // 方法描述
public List<User> query(UserQueryCondition condition) {

定義請求字段信息,如果參數是一個對象,則需要在對象字段上添加註解

public class UserQueryCondition {
    @ApiModelProperty(value = "用戶名")
    private String username;

不是對象的字段描述

@JsonView(User.UserDetailView.class)
public User getInfo(@ApiParam(value = "用戶id") @PathVariable String id) {

上面是3個常用的註解,其他的官網文檔查看;

個人感覺:相對於spring-restdocs-asciidoctor代碼入侵太嚴重,我個人是不太願意用的;但是的確很方便能看到所有提供的服務;包括spring框架提供的

下一節:使用WireMock快速僞造restful服務

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章