1、簡介
Swagger 是一個規範和完整的框架,用於生成、描述、調用和可視化 RESTful 風格的 Web 服務。整體目標是使客戶端和文件系統做爲服務器以一樣的速度來更新 。接口的方法,參數和模型緊密集成到服務器端的代碼,容許API來始終保持同步。Swagger 讓部署管理和使用功能強大的API從未如此簡單。html
咱們的RESTful API就有可能要面對多個開發人員或多個開發團隊:IOS開發、Android開發、Web開發等。爲了減小與其餘團隊平時開發期間的頻繁溝通成本,傳統作法咱們會建立一份RESTful API文檔來記錄全部接口細節,然而這樣的作法有如下幾個問題:java
- 因爲接口衆多,而且細節複雜(須要考慮不一樣的HTTP請求類型、HTTP頭部信息、HTTP請求內容等),高質量地建立這份文檔自己就是件很是吃力的事,下游的抱怨聲不絕於耳;
- 隨着時間推移,不斷修改接口實現的時候都必須同步修改接口文檔,而文檔與代碼又處於兩個不一樣的媒介,除非有嚴格的管理機制,否則很容易致使不一致現象;
而swagger完美的解決了上面的幾個問題,並與Spring MVC程序配合組織出強大RESTful API文檔。它既能夠減小咱們建立文檔的工做量,同時說明內容又整合入實現代碼中,讓維護文檔和修改代碼整合爲一體,可讓咱們在修改代碼邏輯的同時方便的修改文檔說明。另外Swagger2也提供了強大的頁面測試功能 來調試每一個RESTful API。git
2、添加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>
3、建立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信息 * 建立人:XiaChengwei * 建立時間:2017年7月28日 上午10:03:29 * @version 1.0 */
@Configuration //讓Spring來加載該類配置
@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("基礎平臺 RESTful APIs")
.description("基礎平臺 RESTful 風格的接口文檔,內容詳細,極大的減小了先後端的溝通成本,同時確保代碼與文檔保持高度一致,極大的減小維護文檔的時間。")
.termsOfServiceUrl("http://xiachengwei5.coding.me")
.contact("Xia")
.version("1.0.0")
.build();
}
}
4、編寫swagger註解
實體類:github
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 用於在經過對象接收參數時在API文檔中顯示字段的說明 * 註解:@DateTimeFormat 和 @JsonFormat 用於在接收和返回日期格式時將其格式化 * 實體類對應的數據表爲: 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 = "用戶登陸帳號", 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 = "手機號", required = true)
private String userPhone;
@ApiModelProperty(value = "性別")
private Integer userGender;
@ApiModelProperty(value = "記錄建立時間")
@DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss")
private Date createTime;
@ApiModelProperty(value = "記錄修改時間")
@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();
}
}
控制類:web
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 = "查詢全部的人員信息並分頁展現", notes = "查詢全部的人員信息並分頁展現")
@ApiImplicitParams({
@ApiImplicitParam(name = "page",value = "跳轉到的頁數", required = true, paramType = "query"),
@ApiImplicitParam(name = "size",value = "每頁展現的記錄數", 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只對緊跟着的第一個SQL語句起做用
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 = "新增人員前先檢測用戶名是否可用", notes = "新增人員前先檢測用戶名是否可用")
@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())) {
//獲取姓名拼音並存在對象中
userInfoDto.setSpellName(pinyin.getPingYin(userInfoDto.getUserName()));
}else {
return ControllerUtil.returnDto(false, "請輸入姓名", 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:系統異常");
return ControllerUtil.returnDto(false, "系統異常", count);
}
}
@ResponseBody
@RequestMapping(value = "updateByPrimaryKeySelective", method = RequestMethod.POST)
@ApiOperation(value = "根據id修改人員信息", notes = "根據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:系統異常");
return ControllerUtil.returnDto(false, "系統異常", 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 = "驗證碼", 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 {
//先對驗證碼是否正確作驗證(此處暫未處理)
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:系統異常");
return ControllerUtil.returnDto(false, "系統異常", count);
}
}
@ResponseBody
@RequestMapping(value = "deleteByPrimaryKey", method = RequestMethod.GET)
@ApiOperation(value = "根據id刪除人員信息", notes = "根據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:系統異常");
return ControllerUtil.returnDto(false, "系統異常", count);
}
}
@ResponseBody
@RequestMapping(value = "selectById", method = RequestMethod.GET)
@ApiOperation(value = "根據id查詢人員的全部信息", notes = "根據id查詢人員的全部信息")
@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);
}
}
5、訪問
配置完成以後重啓服務器,訪問地址 http://localhost:8080/項目名/swagger-ui.html
,如:spring
http://localhost:8080/spring-mvc/swagger-ui.html
訪問以後的效果圖以下:json
點擊具體的接口展開詳情,效果圖以下:後端
在/userInfo/selectById
接口中輸入相關參數,點擊Try it out 按鈕查看接口的返回值,以下:api
{
"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"
}
}
6、參考資料
源碼地址spring-mvc
swagger2 與 springmvc 整合 生成接口文檔
一步步完成Maven+SpringMVC+SpringFox+Swagger整合示例
Spring MVC中使用 Swagger2 構建Restful API
Spring MVC中使用Swagger生成API文檔和完整項目示例