Swagger使用總結
1. Swagger是什么?
官方說法:Swagger是一個規范和完整的框架,用于生成、描述、調用和可視化 RESTful 風格的 Web 服務。總體目標是使客戶端和文件系統作為服務器以同樣的速度來更新。文件的方法,參數和模型緊密集成到服務器端的代碼,允許API來始終保持同步。
個人覺得,swagger的一個最大的優點是能實時同步api與文檔。在項目開發過程中,發生過多次:修改代碼但是沒有更新文檔,前端還是按照老舊的文檔進行開發,在聯調過程中才發現問題的情況(當然依據開閉原則,對接口的修改是不允許的,但是在項目不穩定階段,這種情況很難避免)。
2. spring boot 集成 Swagger
目前維護的系統是基于springboot框架開發的,因此本文會詳細描述springboot與swagger集成的過程。
3,Swagger使用步驟:
3.1 導入相關的maven依賴
<!-- swagger開始 -->
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger2</artifactId>
<version>2.5.0</version>
</dependency>
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger-ui</artifactId>
<version>2.5.0</version>
</dependency>
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-staticdocs</artifactId>
<version>2.5.0</version>
</dependency>
<!-- swagger結束 -->
3.2 創建相關實體,controller,響應對象,主要看其中的注解的使用。
1 ,@Api(description = "用戶相關接口文檔")每個controller上的注解,表示這個controller主要的業務模塊
2,@ApiOperation(value = "用戶首頁", notes = "訪問頁面")每個方法的注解,表示這個方法的業務功能是什么
3, @ApiParam(name = "userName",value = "用戶昵稱",required = true)方法參數注解,表示這個在這個業務方法中的名稱,生成后的文檔對該字段的說明,同樣支持對象類型(引用類型),通過@ApiModelProperty(value = "用戶id", required = true)來說明引用類型每個屬性的作用。
4,@RequestHeader("token") String token 這個注解可以獲取和設置header的參數,如用戶身份簽名。
controller
package org.kewei.zhang.controllers;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.kewei.zhang.Beans.TbTest;
import org.kewei.zhang.entites.Constants;
import org.kewei.zhang.entites.Result;
import org.kewei.zhang.entites.UserVo;
import org.kewei.zhang.mapper.TbTestMapper;
import org.kewei.zhang.utils.DateUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Random;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
/**
* @author : kewei.zhang
* @Date: 2017/10/19
* @Time: 下午3:00
* Description: 用于處理所有action的統一入口
*/
@SuppressWarnings("ALL")
@RestController
@RequestMapping("/case")
@Api(description = "用戶相關接口文檔")
public class SnCaseController extends BaseController {
@Autowired
private TbTestMapper tbTestMapper;
@GetMapping("/index")
@ApiOperation(value = "用戶首頁", notes = "訪問頁面")
public String index() {
TbTest tbTest = new TbTest();
tbTest.setAge(1);
tbTest.setBrithday(new Date());
tbTest.setHigh(172);
tbTest.setIsboy((short) 1);
tbTest.setName("張克巍");
tbTest.setSchool("皖西學院");
tbTest.setWigth(158);
tbTestMapper.insert(tbTest);
return "index";
}
@RequestMapping(value = "/add", method = RequestMethod.POST)
@ApiOperation(value = "添加用戶", notes = "增加用戶")
public Result<UserVo> add(@ApiParam(name = "token", value = "token",required = true) @RequestParam(name = "token", required = true) String token,
@ApiParam(name = "userName",value = "用戶昵稱",required = true)@RequestParam(name = "userName",required = true)String userName,
@ApiParam(name = "mobile",value = "手機",required = true)@RequestParam(name = "mobile",required = true)String mobile,
@ApiParam(required = true, name = "email", value = "郵箱") @RequestParam(name = "email", required = true) String email ) {
return new Result<UserVo>(Constants.SUCCESS,Constants.MSG_SUCCESS,new UserVo());
}
@RequestMapping(value = {"/toAdd","/testAdd"}, method = RequestMethod.GET)
@ApiOperation(value = "用戶添加", notes = "用戶增加")
public Result<UserVo> toAdd(@ApiParam(name = "token", value = "token",required = true) @RequestParam(name = "token", required = true) String token,
@ApiParam(name = "userName",value = "用戶昵稱",required = true)@RequestParam(name = "userName",required = true)String userName,
@ApiParam(name = "mobile",value = "手機",required = true)@RequestParam(name = "mobile",required = true)String mobile,
@ApiParam(required = true, name = "email", value = "郵箱") @RequestParam(name = "email", required = true) String email ) {
return new Result<UserVo>(Constants.SUCCESS,Constants.MSG_SUCCESS,new UserVo());
}
@RequestMapping(value = "/update", method = RequestMethod.POST)
@ApiOperation(value = "更新用戶", notes = "用戶更新")
public Result<UserVo> update(@ApiParam(name = "user", value = "user",required = true)@RequestBody UserVo userVo ) {
return new Result<UserVo>(Constants.SUCCESS,Constants.MSG_SUCCESS,userVo);
}
@RequestMapping(value = "/getHeader", method = RequestMethod.POST)
@ApiOperation(value = "獲取用戶頭部信息", notes = "獲取用戶頭部信息")
public Result<UserVo> getHeader(@ApiParam(name = "token", value = "用戶身份",required = true)@RequestHeader("token") String token,
@ApiParam(name = "userName",value = "用戶昵稱",required = true)@RequestParam(name = "userName",required = true)String userName,
@ApiParam(name = "mobile",value = "手機",required = true)@RequestParam(name = "mobile",required = true)String mobile) {
UserVo userVo= new UserVo();
userVo.setUserName(token+userName+mobile);
return new Result<UserVo>(Constants.SUCCESS,Constants.MSG_SUCCESS,userVo);
}
}
bean 這里需要注意,如果有boolean類型,要為其添加getXX
X和setXXX方法,不是isXXX,因為swagger不識別isXXX
package org.kewei.zhang.entites;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
/**
* @author: kewei.zhang
* @Date: 2017/12/5
* @Time: 下午3:15
* Description:
*/
@ApiModel(value = "用戶信息")
public class UserVo {
@ApiModelProperty(value = "用戶id", required = true)
private long userId=10;
@ApiModelProperty(value = "昵稱", required = true)
private String userName="張克巍";
public long getUserId() {
return userId;
}
public void setUserId(long userId) {
this.userId = userId;
}
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
}
響應實體
package org.kewei.zhang.entites;
import com.fasterxml.jackson.annotation.JsonInclude;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import java.io.Serializable;
/**
* @author: kewei.zhang
* @Date: 2017/12/5
* @Time: 下午3:11
* Description:
*/
@ApiModel
@JsonInclude(JsonInclude.Include.NON_NULL)
public class Result<T> implements Serializable {
private static final long serialVersionUID = 1L;
// 200成功
@ApiModelProperty(value = "錯誤碼", name = "錯誤碼")
private int code;
// 返回消息,成功為“success”,失敗為具體失敗信息
@ApiModelProperty(value = "錯誤碼描述", name = "錯誤碼描述")
private String desc;
// 返回數據
@ApiModelProperty(value = "數據對象", name = "數據對象")
private T data;
public Result() {
}
public Result(int code, String desc) {
this.code = code;
this.desc = desc;
}
public Result(int code, String desc, T data) {
this.code = code;
this.desc = desc;
this.data = data;
}
public int getCode() {
return code;
}
public void setCode(int code) {
this.code = code;
}
public String getDesc() {
return desc;
}
public void setDesc(String desc) {
this.desc = desc;
}
public T getData() {
return data;
}
public void setData(T data) {
this.data = data;
}
@Override
public String toString() {
return "Result{" +
"code=" + code +
", desc='" + desc + '\'' +
", data=" + data +
'}';
}
}
package org.kewei.zhang.entites;
/**
* @author: kewei.zhang
* @Date: 2017/12/5
* @Time: 下午3:13
* Description:
*/
public interface Constants {
////////////// 系統標識符 開始//////////////////
/**
* 錯誤 描述
*/
String MSG_ERROR = "error";
/**
* 成功 描述
*/
String MSG_SUCCESS = "OK";
////////////// 系統狀態碼 開始//////////////////
/**
* 請求失敗
*/
int ERROR = 100;
/**
* 請求成功
*/
int SUCCESS = 200;
}
3.3 swagger添加配置信息@Configuration@EnableSwagger2
package org.kewei.zhang.config;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.stereotype.Component;
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;
/**
* @author: kewei.zhang
* @Date: 2017/12/5
* @Time: 下午3:04
* Description:
*/
@Configuration
@EnableSwagger2
@Component
public class SwaggerConfig {
@Bean
public Docket userApi() {
return new Docket(DocumentationType.SWAGGER_2)
.groupName("用戶")
.select()
.apis(RequestHandlerSelectors.basePackage("org.kewei.zhang.controller"))// 選擇那些路徑和api會生成document,每個controller都需要添加
.paths(PathSelectors.any()) // 對所有路徑進行監控
.build()
.apiInfo(userInfo());
}
private ApiInfo userInfo() {
ApiInfo apiInfo = new ApiInfo("用戶相關接口",//大標題
"用戶有關的接口,包括增加刪除用戶",//小標題
"0.1",//版本
"上海",
new Contact("zkw", "", ""),// 作者
"swagger url",//鏈接顯示文字
""http://網站鏈接
);
return apiInfo;
}
}
3.4 在瀏覽器中輸入http://ip:port/your-app-root/swagger-ui.html 即可生成相應的文檔并可以隨時測試。
圖中的文字說明都是通過之前的注解添加進去的
上述是完成生成api文檔的具體步驟,但是有這樣幾個問題值得大家思考。
接口文檔生成,需要嵌入我們的項目中,對我們的代碼有侵入,這一點現在避免不了,而且我們只希望用戶在我們的測試環境去測試,不希望生成環境去生成文檔,如何解決這個問題,方法有兩種,如下:
在配置中做管理
@Configuration
@EnableSwagger2
@EnableWebMvc
@ComponentScan("com.XXX.controller")
public class SwaggerConfig{
@Autowired
ConfigService configService;
@Bean
public Docket customDocket() {
if(configService.getServerEnv() == ServerEnvEnum.ONLINE) {
return new Docket(DocumentationType.SWAGGER_2)
.apiInfo(apiInfoOnline())
.select()
.paths(PathSelectors.none())//如果是線上環境,添加路徑過濾,設置為全部都不符合
.build();
}else {
return new Docket(DocumentationType.SWAGGER_2)
.apiInfo(apiInfo());
}
}
private ApiInfo apiInfo() {
return new ApiInfoBuilder()
.title("XXX系統")
.description("XXX系統接口")
.license("")
.licenseUrl("")
.termsOfServiceUrl("")
.version("1.0.0")
.contact(new Contact("","", ""))
.build();
}
private ApiInfo apiInfoOnline() {
return new ApiInfoBuilder()
.title("")
.description("")
.license("")
.licenseUrl("")
.termsOfServiceUrl("")
.version("")
.contact(new Contact("","", ""))
.build();
}
}
另一種方式是:
修改一下依賴,為了編譯通過,單獨把swagger-annotations拿出來,線上環境把springfox-swagger-ui的依賴配置成是provided,這樣可以實現http://localhost/swagger-ui.html訪問404。但是:http://localhost/v2/api-docs和http://localhost/swagger-resources等接口依然能夠訪問,盡管是空的!
<dependency>
<groupId>io.swagger</groupId>
<artifactId>swagger-annotations</artifactId>
<version>${springfox-swagger-anno.version}</version>
</dependency>
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger2</artifactId>
<version>${springfox-swagger.version}</version>
</dependency>
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger-ui</artifactId>
<scope>${swagger.scope}</scope>
<version>${springfox-swagger.version}</version>
</dependency>
<profile>
<id>online</id>
<properties>
<profiles.active>online</profiles.active>
<swagger.scope>provided</swagger.scope>
</properties>
</profile>