天天看點

Spring3 MVC中使用Swagger生成API文檔

Spring3 MVC中使用Swagger生成API文檔

一:Swagger介紹

Swagger是目前最好用的Restful API文檔生成的開源項目,通過swagger-spring項目

實作了與SpingMVC架構的無縫內建功能,友善生成spring restful風格的接口文檔,

同時swagger-ui還可以測試spring restful風格的接口功能。其官方網站為:

<a target="_blank" href="http://swagger.io/">http://swagger.io/</a>

二:Swagger內建Spring3 MVC步驟

Swagger內建springMVC步驟大緻隻有如下幾步:

1.在pom.xml檔案中添加swagger相關的依賴

2.建立classpath路徑下建立一個swagger.properties, 添加如下内容:

documentation.services.version=1.0

documentation.services.basePath=http://localhost:8080/yourcontextpath

3.在springMVC的main-servlet.xml檔案添加如下配置

4.重新打包部署你的項目到WEB伺服器,通路位址

http://localhost:8080/your-contextpath /api-docs即可看到注解生成的API說明

三:常見swagger注解一覽與使用

APIs.@Api

@ApiClass

@ApiError

@ApiErrors

@ApiOperation

@ApiParam

@ApiParamImplicit

@ApiParamsImplicit

@ApiProperty

@ApiResponse

@ApiResponses

@ApiModel

在代碼中使用例子:

四:運作swagger-ui測試接口

下載下傳swagger-ui的最新版本到本地,改名為swagger-ui,把dist下面的部署到tomcat

http://localhost:8080/your-contextpath /api-docs儲存,然後在啟動WEB伺服器,

顯示如下:

Spring3 MVC中使用Swagger生成API文檔

展開輸入參數以後,點選【try it out】即可測試接口,檢視傳回資料。

注意:加上之後啟動報Bean not found mapping之類的錯誤,請在對應

xml檔案中加上如下的配置: