一、簡(jiǎn)介
Swagger 是一個(gè)規(guī)范和完整的框架,用于生成、描述、調(diào)用和可視化 RESTful 風(fēng)格的 Web 服務(wù)??傮w目標(biāo)是使客戶端和文件系統(tǒng)作為服務(wù)器以同樣的速度來(lái)更新 。接口的方法,參數(shù)和模型緊密集成到服務(wù)器端的代碼,允許API來(lái)始終保持同步。Swagger 讓部署管理和使用功能強(qiáng)大的API從未如此簡(jiǎn)單。
我們的RESTful API就有可能要面對(duì)多個(gè)開(kāi)發(fā)人員或多個(gè)開(kāi)發(fā)團(tuán)隊(duì):IOS開(kāi)發(fā)、Android開(kāi)發(fā)、Web開(kāi)發(fā)等。為了減少與其他團(tuán)隊(duì)平時(shí)開(kāi)發(fā)期間的頻繁溝通成本,傳統(tǒng)做法我們會(huì)創(chuàng)建一份RESTful API文檔來(lái)記錄所有接口細(xì)節(jié),然而這樣的做法有以下幾個(gè)問(wèn)題:
- 由于接口眾多,并且細(xì)節(jié)復(fù)雜(需要考慮不同的HTTP請(qǐng)求類型、HTTP頭部信息、HTTP請(qǐng)求內(nèi)容等),高質(zhì)量地創(chuàng)建這份文檔本身就是件非常吃力的事,下游的抱怨聲不絕于耳;
- 隨著時(shí)間推移,不斷修改接口實(shí)現(xiàn)的時(shí)候都必須同步修改接口文檔,而文檔與代碼又處于兩個(gè)不同的媒介,除非有嚴(yán)格的管理機(jī)制,不然很容易導(dǎo)致不一致現(xiàn)象;
而swagger完美的解決了上面的幾個(gè)問(wèn)題,并與Spring MVC程序配合組織出強(qiáng)大RESTful API文檔。它既可以減少我們創(chuàng)建文檔的工作量,同時(shí)說(shuō)明內(nèi)容又整合入實(shí)現(xiàn)代碼中,讓維護(hù)文檔和修改代碼整合為一體,可以讓我們?cè)谛薷拇a邏輯的同時(shí)方便的修改文檔說(shuō)明。另外Swagger2也提供了強(qiáng)大的頁(yè)面測(cè)試功能 來(lái)調(diào)試每個(gè)RESTful API。
二、添加Swagger2依賴
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger2</artifactId>
<version>2.6.1</version>
</dependency>
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger-ui</artifactId>
<version>2.6.1</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-core</artifactId>
<version>2.6.5</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.6.5</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-annotations</artifactId>
<version>2.6.5</version>
</dependency>
三、創(chuàng)建Swagger2配置類
package com.xia.common.config;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import io.swagger.annotations.ApiOperation;
import springfox.documentation.builders.ApiInfoBuilder;
import springfox.documentation.builders.PathSelectors;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.service.ApiInfo;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2;
/**
* 類描述:配置swagger2信息
* 創(chuàng)建人:XiaChengwei
* 創(chuàng)建時(shí)間:2017年7月28日 上午10:03:29
* @version 1.0
*/
@Configuration //讓Spring來(lái)加載該類配置
@EnableWebMvc //啟用Mvc,非springboot框架需要引入注解@EnableWebMvc
@EnableSwagger2 //啟用Swagger2
public class Swagger2Config {
@Bean
public Docket createRestApi() {
return new Docket(DocumentationType.SWAGGER_2)
.apiInfo(apiInfo()).select()
//掃描指定包中的swagger注解
//.apis(RequestHandlerSelectors.basePackage("com.xia.controller"))
//掃描所有有注解的api,用這種方式更靈活
.apis(RequestHandlerSelectors.withMethodAnnotation(ApiOperation.class))
.paths(PathSelectors.any())
.build();
}
private ApiInfo apiInfo() {
return new ApiInfoBuilder()
.title("基礎(chǔ)平臺(tái) RESTful APIs")
.description("基礎(chǔ)平臺(tái) RESTful 風(fēng)格的接口文檔,內(nèi)容詳細(xì),極大的減少了前后端的溝通成本,同時(shí)確保代碼與文檔保持高度一致,極大的減少維護(hù)文檔的時(shí)間。")
.termsOfServiceUrl("http://xiachengwei5.coding.me")
.contact("Xia")
.version("1.0.0")
.build();
}
}
四、編寫(xiě)swagger注解
實(shí)體類:
package com.xia.model;
import java.util.Date;
import org.springframework.format.annotation.DateTimeFormat;
import com.fasterxml.jackson.annotation.JsonFormat;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.fasterxml.jackson.annotation.JsonInclude;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
/**
* 人員信息表
* 注解:@ApiModel 和 @ApiModelProperty 用于在通過(guò)對(duì)象接收參數(shù)時(shí)在API文檔中顯示字段的說(shuō)明
* 注解:@DateTimeFormat 和 @JsonFormat 用于在接收和返回日期格式時(shí)將其格式化
* 實(shí)體類對(duì)應(yīng)的數(shù)據(jù)表為: user_info
* @author XiaChengwei
* @date: 2017-07-14 16:45:29
*/
@JsonInclude(JsonInclude.Include.NON_NULL)
@JsonIgnoreProperties({ "handler","hibernateLazyInitializer" })
@ApiModel(value ="UserInfo")
public class UserInfo {
@ApiModelProperty(value = "ID")
private Integer id;
@ApiModelProperty(value = "用戶登錄賬號(hào)", required = true)
private String userNo;
@ApiModelProperty(value = "姓名", required = true)
private String userName;
@ApiModelProperty(value = "姓名拼音")
private String spellName;
@ApiModelProperty(value = "密碼", required = true)
private String password;
@ApiModelProperty(value = "手機(jī)號(hào)", required = true)
private String userPhone;
@ApiModelProperty(value = "性別")
private Integer userGender;
@ApiModelProperty(value = "記錄創(chuàng)建時(shí)間")
@DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss")
private Date createTime;
@ApiModelProperty(value = "記錄修改時(shí)間")
@DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss")
private Date updateTime;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getUserNo() {
return userNo;
}
public void setUserNo(String userNo) {
this.userNo = userNo == null ? null : userNo.trim();
}
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName == null ? null : userName.trim();
}
public String getSpellName() {
return spellName;
}
public void setSpellName(String spellName) {
this.spellName = spellName;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password == null ? null : password.trim();
}
public String getUserPhone() {
return userPhone;
}
public void setUserPhone(String userPhone) {
this.userPhone = userPhone == null ? null : userPhone.trim();
}
public Integer getUserGender() {
return userGender;
}
public void setUserGender(Integer userGender) {
this.userGender = userGender;
}
@JsonFormat(locale = "zh", timezone = "GMT+8", pattern = "yyyy-MM-dd HH:mm:ss")
public Date getCreateTime() {
return createTime;
}
public void setCreateTime(Date createTime) {
this.createTime = createTime;
}
@JsonFormat(locale = "zh", timezone = "GMT+8", pattern = "yyyy-MM-dd HH:mm:ss")
public Date getUpdateTime() {
return updateTime;
}
public void setUpdateTime(Date updateTime) {
this.updateTime = updateTime;
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append(getClass().getSimpleName());
sb.append(" [");
sb.append("Hash = ").append(hashCode());
sb.append(", id=").append(id);
sb.append(", userNo=").append(userNo);
sb.append(", userName=").append(userName);
sb.append(", spellName=").append(spellName);
sb.append(", password=").append(password);
sb.append(", userPhone=").append(userPhone);
sb.append(", userGender=").append(userGender);
sb.append(", createTime=").append(createTime);
sb.append(", updateTime=").append(updateTime);
sb.append("]");
return sb.toString();
}
}
控制類:
package com.infore.controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.infore.common.pinyin.PinyinUtils;
import com.infore.common.util.ControllerUtil;
import com.infore.model.ResponseDto;
import com.infore.model.UserInfo;
import com.infore.model.dto.UserInfoDto;
import com.infore.service.UserInfoService;
import gbap.log.Logger;
import gbap.log.LoggerFactory;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import java.util.List;
import javax.annotation.Resource;
import javax.ws.rs.core.MediaType;
/**
* 人員信息控制類
* @author XiaChengwei
* @date: 2017-07-14 16:45:29
*/
@RestController
@RequestMapping(value = "/userInfo", produces = MediaType.APPLICATION_JSON)
@Api(value = "用戶信息", description = "用戶信息", produces = MediaType.APPLICATION_JSON)
public class UserInfoController {
private Logger logger = LoggerFactory.getLogger(getClass());
@Resource
UserInfoService service;
@ResponseBody
@RequestMapping(value = "/selectAllUsers", method = RequestMethod.GET)
@ApiOperation(value = "查詢所有的人員信息并分頁(yè)展示", notes = "查詢所有的人員信息并分頁(yè)展示")
@ApiImplicitParams({
@ApiImplicitParam(name = "page",value = "跳轉(zhuǎn)到的頁(yè)數(shù)", required = true, paramType = "query"),
@ApiImplicitParam(name = "size",value = "每頁(yè)展示的記錄數(shù)", required = true, paramType = "query")
})
public ResponseDto selectAllUsers(Integer page, Integer size) {
page = page == null || page <= 0 ? 1 : page;
size = size == null || size <= 5 ? 5 : size;
PageHelper.startPage(page, size);//PageHelper只對(duì)緊跟著的第一個(gè)SQL語(yǔ)句起作用
List<UserInfo> userInfoList = service.selectAllUsers();
PageInfo pageInfo = new PageInfo(userInfoList);
return ControllerUtil.returnDto(true, "成功", pageInfo);
}
@ResponseBody
@RequestMapping(value = "/selectContacts", method = RequestMethod.GET)
@ApiOperation(value = "查詢通訊錄人員信息", notes = "查詢通訊錄人員信息")
public ResponseDto selectContacts() {
List<UserInfo> list = service.selectContacts();
return ControllerUtil.returnDto(true, "成功", list);
}
@ResponseBody
@RequestMapping(value = "selectByUserNo", method = RequestMethod.GET)
@ApiOperation(value = "新增人員前先檢測(cè)用戶名是否可用", notes = "新增人員前先檢測(cè)用戶名是否可用")
@ApiImplicitParams({
@ApiImplicitParam(name = "user_no", value = "用戶輸入的用戶名", required = true, paramType = "query")
})
public ResponseDto selectByUserNo(String user_no) {
UserInfo userInfo = service.selectByUserNo(user_no);
if(null == userInfo || "".equals(userInfo.getUserNo())) {
return ControllerUtil.returnDto(true, "此用戶名可用", null);
}else {
return ControllerUtil.returnDto(false, "此用戶名不可用", null);
}
}
@ResponseBody
@RequestMapping(value = "insertSelective", method = RequestMethod.POST)
@ApiOperation(value = "新增人員", notes = "新增人員")
public ResponseDto insertSelective(UserInfoDto userInfoDto) {
int count = 0;
PinyinUtils pinyin = new PinyinUtils();
try {
//新增人員之前先檢查用戶名是否可用
UserInfo userInfo = service.selectByUserNo(userInfoDto.getUserNo());
if(null != userInfo && !"".equals(userInfo.getUserNo())) {
return ControllerUtil.returnDto(false, "此用戶名不可用", null);
}
if(null != userInfoDto.getUserName() && !"".equals(userInfoDto.getUserName())) {
//獲取姓名拼音并存在對(duì)象中
userInfoDto.setSpellName(pinyin.getPingYin(userInfoDto.getUserName()));
}else {
return ControllerUtil.returnDto(false, "請(qǐng)輸入姓名", count);
}
count = service.insertSelective(userInfoDto);
if(count <= 0) {
return ControllerUtil.returnDto(false, "失敗", count);
}else {
return ControllerUtil.returnDto(true, "成功", count);
}
} catch (Exception e) {
logger.error("userInfo--insertSelective:系統(tǒng)異常");
return ControllerUtil.returnDto(false, "系統(tǒng)異常", count);
}
}
@ResponseBody
@RequestMapping(value = "updateByPrimaryKeySelective", method = RequestMethod.POST)
@ApiOperation(value = "根據(jù)id修改人員信息", notes = "根據(jù)id修改人員信息")
public ResponseDto updateByPrimaryKeySelective(UserInfoDto userInfoDto) {
int count = 0;
try {
count = service.updateByPrimaryKeySelective(userInfoDto);
if(count <= 0) {
return ControllerUtil.returnDto(false, "失敗", count);
}else {
return ControllerUtil.returnDto(true, "成功", count);
}
} catch (Exception e) {
logger.error("userInfo--updateByPrimaryKeySelective:系統(tǒng)異常");
return ControllerUtil.returnDto(false, "系統(tǒng)異常", count);
}
}
@ResponseBody
@RequestMapping(value = "modifyPwdById", method = RequestMethod.GET)
@ApiOperation(value = "修改密碼", notes = "修改密碼")
@ApiImplicitParams({
@ApiImplicitParam(name = "id",value = "人員信息id", required = true, paramType = "query"),
@ApiImplicitParam(name = "security_code",value = "驗(yàn)證碼", required = true, paramType = "query"),
@ApiImplicitParam(name = "password",value = "新密碼", required = true, paramType = "query")
})
public ResponseDto updateByPrimaryKeySelective(Integer id, String security_code, String password) {
int count = 0;
try {
//先對(duì)驗(yàn)證碼是否正確做驗(yàn)證(此處暫未處理)
UserInfoDto userInfoDto = new UserInfoDto();
userInfoDto.setId(id);
userInfoDto.setPassword(password);
count = service.modifyPwdById(userInfoDto);
if(count <= 0) {
return ControllerUtil.returnDto(false, "失敗", count);
}else {
return ControllerUtil.returnDto(true, "成功", count);
}
} catch (Exception e) {
logger.error("userInfo--modifyPwdById:系統(tǒng)異常");
return ControllerUtil.returnDto(false, "系統(tǒng)異常", count);
}
}
@ResponseBody
@RequestMapping(value = "deleteByPrimaryKey", method = RequestMethod.GET)
@ApiOperation(value = "根據(jù)id刪除人員信息", notes = "根據(jù)id刪除人員信息")
@ApiImplicitParams({
@ApiImplicitParam(name = "id", value = "人員信息id", required = true, paramType = "query")
})
public ResponseDto deleteByPrimaryKey(Integer id) {
int count = 0;
try {
count = service.deleteByPrimaryKey(id);
if(count <= 0) {
return ControllerUtil.returnDto(false, "失敗", count);
}else {
return ControllerUtil.returnDto(true, "成功", count);
}
} catch (Exception e) {
logger.error("userInfo--deleteByPrimaryKey:系統(tǒng)異常");
return ControllerUtil.returnDto(false, "系統(tǒng)異常", count);
}
}
@ResponseBody
@RequestMapping(value = "selectById", method = RequestMethod.GET)
@ApiOperation(value = "根據(jù)id查詢?nèi)藛T的所有信息", notes = "根據(jù)id查詢?nèi)藛T的所有信息")
@ApiImplicitParams({
@ApiImplicitParam(name = "id", value = "人員信息id", required = true, paramType = "query")
})
public ResponseDto selectById(Integer id) {
UserInfoDto dto = service.selectById(id);
return ControllerUtil.returnDto(true, "成功", dto);
}
}
五、訪問(wèn)
配置完成之后重啟服務(wù)器,訪問(wèn)地址 http://localhost:8080/項(xiàng)目名/swagger-ui.html
,如:
http://localhost:8080/spring-mvc/swagger-ui.html
訪問(wèn)之后的效果圖如下:
點(diǎn)擊具體的接口展開(kāi)詳情,效果圖如下:
在/userInfo/selectById
接口中輸入相關(guān)參數(shù),點(diǎn)擊Try it out 按鈕查看接口的返回值,如下:
{
"success": true,
"msg": "成功",
"data": {
"id": 1,
"userNo": "admin",
"userName": "管理員",
"spellName": "guanliyuan",
"password": "123",
"userPhone": "18681558780",
"userGender": 0,
"createTime": "2017-06-27 01:56:28",
"updateTime": "2017-07-26 15:56:05"
}
}
六、參考資料
swagger2 與 springmvc 整合 生成接口文檔
一步步完成Maven+SpringMVC+SpringFox+Swagger整合示例
Spring MVC中使用 Swagger2 構(gòu)建Restful API
Spring MVC中使用Swagger生成API文檔和完整項(xiàng)目示例