Swagger是一個先後端分離下使用的API接口框架,它提供了RESTful 風格的接口生成、描述、調用和可視化。Swagger 的目標是對 REST API 定義一個標準且和語言無關的接口,可讓人和計算機擁有無須訪問源碼、文檔或網絡流量監測就能夠發現和理解服務的能力。當經過 Swagger 進行正肯定義,用戶能夠理解遠程服務並使用最少實現邏輯與遠程服務進行交互。與爲底層編程所實現的接口相似,Swagger 消除了調用服務時可能會有的猜想。swagger是一款讓你更好的書寫api文檔的框架。html
1)支持 API 自動生成同步的在線文檔:使用 Swagger 後能夠直接經過代碼生成文檔,再也不須要本身手動編寫接口文檔了,對程序員來講很是方便,能夠節約寫文檔的時間去學習新技術。java
2)提供 Web 頁面在線測試 API:光有文檔還不夠,Swagger 生成的文檔還支持在線測試。參數和格式都定好了,直接在界面上輸入參數對應的值便可在線測試接口。程序員
1)建立一個springboot項目,引入web依賴web
2)在pom文件加入下面這些依賴spring
<dependency> <groupId>io.springfox</groupId> <artifactId>springfox-swagger2</artifactId> <version>2.8.0</version> </dependency> <dependency> <groupId>io.springfox</groupId> <artifactId>springfox-swagger-ui</artifactId> <version>2.8.0</version> </dependency> <dependency> <groupId>com.fasterxml.jackson.core</groupId> <artifactId>jackson-databind</artifactId> <version>2.2.6</version> </dependency>
3)寫一個簡單類加上兩個註解apache
@Configuration @EnableSwagger2 //開啓swagger2 public class Swagger2 { }
4)訪問http://localhost:8080/swagger-ui.html就能夠看到swagger頁面編程
5)配置Swagger2類後端
package com.gh.swagger;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import springfox.documentation.builders.PathSelectors;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.service.ApiInfo;
import springfox.documentation.service.Contact;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2;
import java.util.ArrayList;
@Configuration
@EnableSwagger2 //開啓swagger2
//@EnableWebMvc
public class Swagger2 {
@Bean
public Docket createRestApi() {
return new Docket(DocumentationType.SWAGGER_2)
.apiInfo(apiInfo())
.select()
//爲當前包路徑
.apis(RequestHandlerSelectors.basePackage("com.jiang"))
.paths(PathSelectors.any())
.build();
}
//構建 api文檔的詳細信息函數,注意這裏的註解引用的是哪一個
private ApiInfo apiInfo() {
Contact concact = new Contact("fang", "http://www.baidu.com", "1179508986@qq.com");
return new ApiInfo(
"我是中國",
"所示",
"v1.0",
"http://www.baidu.com",
concact,
"Apache 2.0",
"http://www.apache.org/licenses/LICENSE-2.0",
new ArrayList<>()
);
}
}
6)swagger配置掃描接口api
.apis(RequestHandlerSelectors.basePackage("com.gh.controller")) //RequestHandlerSelectors配置要掃描接口的方式,basePackage指定要掃描的包springboot
.paths //過濾什麼路徑
.enable(false) //配置不啓動
.groupName()
@Api:用在類上,說明該類的做用。@ApiOperation:註解來給API增長方法說明。@ApiImplicitParams : 用在方法上包含一組參數說明。@ApiImplicitParam:用來註解來給方法入參增長說明。@ApiResponses:用於表示一組響應@ApiResponse:用在@ApiResponses中,通常用於表達一個錯誤的響應信息