SpringMVC集成Swagger插件以及Swagger注解的簡單使用

一、簡介

Swagger 是一個規(guī)范和完整的框架,用于生成、描述、調(diào)用和可視化 RESTful 風格的 Web 服務。總體目標是使客戶端和文件系統(tǒng)作為服務器以同樣的速度來更新 。接口的方法,參數(shù)和模型緊密集成到服務器端的代碼,允許API來始終保持同步。Swagger 讓部署管理和使用功能強大的API從未如此簡單。

我們的RESTful API就有可能要面對多個開發(fā)人員或多個開發(fā)團隊:IOS開發(fā)、Android開發(fā)、Web開發(fā)等。為了減少與其他團隊平時開發(fā)期間的頻繁溝通成本,傳統(tǒng)做法我們會創(chuàng)建一份RESTful API文檔來記錄所有接口細節(jié),然而這樣的做法有以下幾個問題:

  1. 由于接口眾多,并且細節(jié)復雜(需要考慮不同的HTTP請求類型、HTTP頭部信息、HTTP請求內(nèi)容等),高質(zhì)量地創(chuàng)建這份文檔本身就是件非常吃力的事,下游的抱怨聲不絕于耳;
  2. 隨著時間推移,不斷修改接口實現(xiàn)的時候都必須同步修改接口文檔,而文檔與代碼又處于兩個不同的媒介,除非有嚴格的管理機制,不然很容易導致不一致現(xiàn)象;

而swagger完美的解決了上面的幾個問題,并與Spring MVC程序配合組織出強大RESTful API文檔。它既可以減少我們創(chuàng)建文檔的工作量,同時說明內(nèi)容又整合入實現(xiàn)代碼中,讓維護文檔和修改代碼整合為一體,可以讓我們在修改代碼邏輯的同時方便的修改文檔說明。另外Swagger2也提供了強大的頁面測試功能 來調(diào)試每個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)建時間: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("基礎(chǔ)平臺 RESTful APIs")
                .description("基礎(chǔ)平臺 RESTful 風格的接口文檔,內(nèi)容詳細,極大的減少了前后端的溝通成本,同時確保代碼與文檔保持高度一致,極大的減少維護文檔的時間。")
                .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 用于在通過對象接收參數(shù)時在API文檔中顯示字段的說明
 * 注解:@DateTimeFormat 和 @JsonFormat 用于在接收和返回日期格式時將其格式化
 * 實體類對應的數(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 = "用戶登錄賬號", 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 = "記錄創(chuàng)建時間")
    @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 = "跳轉(zhuǎn)到的頁數(shù)", required = true, paramType = "query"),
        @ApiImplicitParam(name = "size",value = "每頁展示的記錄數(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只對緊跟著的第一個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:系統(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 = "驗證碼", 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:系統(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);
    }
}

五、訪問

配置完成之后重啟服務器,訪問地址 http://localhost:8080/項目名/swagger-ui.html,如:

http://localhost:8080/spring-mvc/swagger-ui.html

訪問之后的效果圖如下:

訪問效果圖

點擊具體的接口展開詳情,效果圖如下:

新增人員接口

/userInfo/selectById 接口中輸入相關(guān)參數(shù),點擊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文檔和完整項目示例

SwaggerUI用戶手冊

七、拓展延伸

RAP

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內(nèi)容

  • Spring Cloud為開發(fā)人員提供了快速構(gòu)建分布式系統(tǒng)中一些常見模式的工具(例如配置管理,服務發(fā)現(xiàn),斷路器,智...
    卡卡羅2017閱讀 134,973評論 19 139
  • Spring Boot 參考指南 介紹 轉(zhuǎn)載自:https://www.gitbook.com/book/qbgb...
    毛宇鵬閱讀 46,970評論 6 342
  • Android 自定義View的各種姿勢1 Activity的顯示之ViewRootImpl詳解 Activity...
    passiontim閱讀 173,466評論 25 708
  • 恭喜 真拭悟慧 獲得得到15專欄分享群的首期“周末原創(chuàng)分享”活動的第一名! 獲獎文章: 要不要樹立目標?我終于找到...
    GEEKYANG閱讀 734評論 0 0