描述
Swagger 是一個規范和完整的框架,用于生成、描述、調用和可視化 RESTful 風格的 Web 服務。
總體目標是使客戶端和文件系統作為服務器以同樣的速度來更新。文件的方法、參數和模型緊密集成到服務器端的代碼,允許 API 來始終保持同步。Swagger 讓部署管理和使用功能強大的 API 從未如此簡單。
配置
1、引入相關jar包:
1
2
3
4
5
6
7
8
9
10
|
<dependency> <groupId>io.springfox</groupId> <artifactId>springfox-swagger2</artifactId> <version> 2.7 . 0 </version> </dependency> <dependency> <groupId>io.springfox</groupId> <artifactId>springfox-swagger-ui</artifactId> <version> 2.7 . 0 </version> </dependency> |
2、創建java配置類
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
|
@Configuration @EnableSwagger2 public class Swagger2 { private ApiInfo apiInfo() { return new ApiInfoBuilder() // 文檔標題 .title( "wish" ) // 文檔描述 .description( "https://github.com/handexing" ).termsOfServiceUrl( "https://github.com/handexing" ) .version( "v1" ) .build(); } @Bean public Docket createRestApi() { return new Docket(DocumentationType.SWAGGER_2) .apiInfo(apiInfo()) .select() // 指定controller存放的目錄路徑 .apis(RequestHandlerSelectors.basePackage( "com.wish.controller" )) .paths(PathSelectors.any()) .build(); } } |
3、編寫接口文檔測試
1
2
3
4
5
6
7
8
9
10
11
|
@RequestMapping (value = "testSawgger" , method = RequestMethod.POST, produces = "application/json; charset=utf-8" ) @ApiOperation (value = "測試swagger" , httpMethod = "POST" , notes = "testSawgger" ) public ExecuteResult<Boolean> addUser( @ApiParam (value = "參數" , required = true ) Long id) { ExecuteResult<Boolean> result = new ExecuteResult<Boolean>(); try { result.setSuccess( true ); } catch (Exception e) { result.setSuccess( false ); } return result; } |
說明:
@ApiOperation:用在方法之上
1、value: 表示接口名稱
2、notes: 表示接口詳細描述
3、httpMethod:表示接口請求方法類型
@ApiParam:用在方法參數上
1、required:表示參數是否必須傳
2、name:表示參數名稱
3、value:表示參數描述
測試
swagger2文檔的默認地址是 /swagger-ui.html, 本地開發的訪問http://localhost:8080/swagger-ui.html就可以看到自動生成的文檔了
結語
到這就配置好了,最終demo可查看 源碼地址
總結
以上所述是小編給大家介紹的SpringMVC和Swagger整合方法,希望對大家有所幫助,如果大家有任何疑問請給我留言,小編會及時回復大家的。在此也非常感謝大家對服務器之家網站的支持!
原文鏈接:http://www.jianshu.com/p/610fec589bc0