SpringMVC整合Swagger外掛以及Swagger註解的簡單使用
一、簡介
Swagger 是一個規範和完整的框架,用於生成、描述、呼叫和視覺化 RESTful 風格的 Web 服務。總體目標是使客戶端和檔案系統作為伺服器以同樣的速度來更新 。介面的方法,引數和模型緊密整合到伺服器端的程式碼,允許API來始終保持同步。Swagger 讓部署管理和使用功能強大的API從未如此簡單。
我們的RESTful API就有可能要面對多個開發人員或多個開發團隊:IOS開發、Android開發、Web開發等。為了減少與其他團隊平時開發期間的頻繁溝通成本,傳統做法我們會建立一份RESTful API文件來記錄所有介面細節,然而這樣的做法有以下幾個問題:
- 由於介面眾多,並且細節複雜(需要考慮不同的HTTP請求型別、HTTP頭部資訊、HTTP請求內容等),高質量地建立這份文件本身就是件非常吃力的事,下游的抱怨聲不絕於耳;
- 隨著時間推移,不斷修改介面實現的時候都必須同步修改介面文件,而文件與程式碼又處於兩個不同的媒介,除非有嚴格的管理機制,不然很容易導致不一致現象;
而swagger完美的解決了上面的幾個問題,並與Spring MVC程式配合組織出強大RESTful API文件。它既可以減少我們建立文件的工作量,同時說明內容又整合入實現程式碼中,讓維護文件和修改程式碼整合為一體,可以讓我們在修改程式碼邏輯的同時方便的修改文件說明。另外Swagger2也提供了強大的頁面測試功能 來除錯每個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>
三、建立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();
}
}
四、編寫swagger註解
實體類:
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();
}
}
控制類:
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);
}
}
五、訪問
配置完成之後重啟伺服器,訪問地址 http://localhost:8080/專案名/swagger-ui.html
,如:
http://localhost:8080/spring-mvc/swagger-ui.html
訪問之後的效果圖如下:
訪問效果圖
點選具體的介面展開詳情,效果圖如下:
新增人員介面
在/userInfo/selectById
介面中輸入相關引數,點選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 構建Restful API
Spring MVC中使用Swagger生成API文件和完整專案示例