springboot結合swagger

1:認識Swagger

Swagger 是一個規範和完整的框架,用於生成、描述、調用和可視化 RESTful 風格的 Web 服務。整體目標是使客戶端和文件系統做爲服務器以一樣的速度來更新。文件的方法,參數和模型緊密集成到服務器端的代碼,容許API來始終保持同步。html

 做用:java

    1. 接口的文檔在線自動生成。node

    2. 功能測試。git

 Swagger是一組開源項目,其中主要要項目以下:github

1.   Swagger-tools:提供各類與Swagger進行集成和交互的工具。例如模式檢驗、Swagger 1.2文檔轉換成Swagger 2.0文檔等功能。web

2.   Swagger-core: 用於Java/Scala的的Swagger實現。與JAX-RS(Jersey、Resteasy、CXF...)、Servlets和Play框架進行集成。spring

3.   Swagger-js: 用於JavaScript的Swagger實現。express

4.   Swagger-node-express: Swagger模塊,用於node.js的Express web應用框架。api

5.   Swagger-ui:一個無依賴的HTML、JS和CSS集合,能夠爲Swagger兼容API動態生成優雅文檔。springboot

6.   Swagger-codegen:一個模板驅動引擎,經過分析用戶Swagger資源聲明以各類語言生成客戶端代碼。

 

2:Maven

版本號請根據實際狀況自行更改。

<dependency>

    <groupId>io.springfox</groupId>

    <artifactId>springfox-swagger2</artifactId>

    <version>2.2.2</version>

</dependency>

<dependency>

    <groupId>io.springfox</groupId>

    <artifactId>springfox-swagger-ui</artifactId>

    <version>2.2.2</version>

</dependency>

 

3:建立Swagger2配置類

在Application.java同級建立Swagger2的配置類Swagger2

  1.  
    package com.swaggerTest;
  2.  
     
  3.  
    import org.springframework.context.annotation.Bean;
  4.  
    import org.springframework.context.annotation.Configuration;
  5.  
     
  6.  
    import springfox.documentation.builders.ApiInfoBuilder;
  7.  
    import springfox.documentation.builders.PathSelectors;
  8.  
    import springfox.documentation.builders.RequestHandlerSelectors;
  9.  
    import springfox.documentation.service.ApiInfo;
  10.  
    import springfox.documentation.spi.DocumentationType;
  11.  
    import springfox.documentation.spring.web.plugins.Docket;
  12.  
    import springfox.documentation.swagger2.annotations.EnableSwagger2;
  13.  
     
  14.  
    /**
  15.  
    * Swagger2配置類
  16.  
    * 在與spring boot集成時,放在與Application.java同級的目錄下。
  17.  
    * 經過@Configuration註解,讓Spring來加載該類配置。
  18.  
    * 再經過@EnableSwagger2註解來啓用Swagger2。
  19.  
    */
  20.  
    @Configuration
  21.  
    @EnableSwagger2
  22.  
    public class Swagger2 {
  23.  
     
  24.  
    /**
  25.  
    * 建立API應用
  26.  
    * apiInfo() 增長API相關信息
  27.  
    * 經過select()函數返回一個ApiSelectorBuilder實例,用來控制哪些接口暴露給Swagger來展示,
  28.  
    * 本例採用指定掃描的包路徑來定義指定要創建API的目錄。
  29.  
    *
  30.  
    * @return
  31.  
    */
  32.  
    @Bean
  33.  
    public Docket createRestApi() {
  34.  
    return new Docket(DocumentationType.SWAGGER_2)
  35.  
    .apiInfo(apiInfo())
  36.  
    .select()
  37.  
    .apis(RequestHandlerSelectors.basePackage("com.swaggerTest.controller"))
  38.  
    .paths(PathSelectors.any())
  39.  
    .build();
  40.  
    }
  41.  
     
  42.  
    /**
  43.  
    * 建立該API的基本信息(這些基本信息會展示在文檔頁面中)
  44.  
    * 訪問地址:http://項目實際地址/swagger-ui.html
  45.  
    * @return
  46.  
    */
  47.  
    private ApiInfo apiInfo() {
  48.  
    return new ApiInfoBuilder()
  49.  
    .title("Spring Boot中使用Swagger2構建RESTful APIs")
  50.  
    .description("更多請關注http://www.baidu.com")
  51.  
    .termsOfServiceUrl("http://www.baidu.com")
  52.  
    .contact("sunf")
  53.  
    .version("1.0")
  54.  
    .build();
  55.  
    }
  56.  
    }

如上代碼所示,經過createRestApi函數建立Docket的Bean以後,apiInfo()用來建立該Api的基本信息(這些基本信息會展示在文檔頁面中)。

 

4:添加文檔內容

在完成了上述配置後,其實已經能夠生產文檔內容,可是這樣的文檔主要針對請求自己,描述的主要來源是函數的命名,對用戶並不友好,咱們一般須要本身增長一些說明來豐富文檔內容。

 

Swagger使用的註解及其說明:

@Api:用在類上,說明該類的做用。

@ApiOperation:註解來給API增長方法說明。

@ApiImplicitParams : 用在方法上包含一組參數說明。

@ApiImplicitParam:用來註解來給方法入參增長說明。

@ApiResponses:用於表示一組響應

@ApiResponse:用在@ApiResponses中,通常用於表達一個錯誤的響應信息

    l   code:數字,例如400

    l   message:信息,例如"請求參數沒填好"

    l   response:拋出異常的類   

@ApiModel:描述一個Model的信息(通常用在請求參數沒法使用@ApiImplicitParam註解進行描述的時候)

    l   @ApiModelProperty:描述一個model的屬性

 

注意:@ApiImplicitParam的參數說明:

paramType:指定參數放在哪一個地方

header:請求參數放置於Request Header,使用@RequestHeader獲取

query:請求參數放置於請求地址,使用@RequestParam獲取

path:(用於restful接口)-->請求參數的獲取:@PathVariable

body:(不經常使用)

form(不經常使用)

name:參數名

 

dataType:參數類型

 

required:參數是否必須傳

true | false

value:說明參數的意思

 

defaultValue:參數的默認值

 

例子:

  1.  
    package com.swaggerTest.controller;
  2.  
     
  3.  
    import org.springframework.stereotype.Controller;
  4.  
    import org.springframework.util.StringUtils;
  5.  
    import org.springframework.web.bind.annotation.RequestMapping;
  6.  
    import org.springframework.web.bind.annotation.RequestMethod;
  7.  
    import org.springframework.web.bind.annotation.RequestParam;
  8.  
    import org.springframework.web.bind.annotation.ResponseBody;
  9.  
     
  10.  
    import io.swagger.annotations.Api;
  11.  
    import io.swagger.annotations.ApiImplicitParam;
  12.  
    import io.swagger.annotations.ApiImplicitParams;
  13.  
    import io.swagger.annotations.ApiOperation;
  14.  
     
  15.  
    /**
  16.  
    * 一個用來測試swagger註解的控制器
  17.  
    * 注意@ApiImplicitParam的使用會影響程序運行,若是使用不當可能形成控制器收不到消息
  18.  
    *
  19.  
    * @author SUNF
  20.  
    */
  21.  
    @Controller
  22.  
    @RequestMapping("/say")
  23.  
    @Api(value = "SayController|一個用來測試swagger註解的控制器")
  24.  
    public class SayController {
  25.  
     
  26.  
    @ResponseBody
  27.  
    @RequestMapping(value ="/getUserName", method= RequestMethod.GET)
  28.  
    @ApiOperation(value="根據用戶編號獲取用戶姓名", notes="test: 僅1和2有正確返回")
  29.  
    @ApiImplicitParam(paramType="query", name = "userNumber", value = "用戶編號", required = true, dataType = "Integer")
  30.  
    public String getUserName(@RequestParam Integer userNumber){
  31.  
    if(userNumber == 1){
  32.  
    return "張三丰";
  33.  
    }
  34.  
    else if(userNumber == 2){
  35.  
    return "慕容復";
  36.  
    }
  37.  
    else{
  38.  
    return "未知";
  39.  
    }
  40.  
    }
  41.  
     
  42.  
    @ResponseBody
  43.  
    @RequestMapping("/updatePassword")
  44.  
    @ApiOperation(value="修改用戶密碼", notes="根據用戶id修改密碼")
  45.  
    @ApiImplicitParams({
  46.  
    @ApiImplicitParam(paramType="query", name = "userId", value = "用戶ID", required = true, dataType = "Integer"),
  47.  
    @ApiImplicitParam(paramType="query", name = "password", value = "舊密碼", required = true, dataType = "String"),
  48.  
    @ApiImplicitParam(paramType="query", name = "newPassword", value = "新密碼", required = true, dataType = "String")
  49.  
    })
  50.  
    public String updatePassword(@RequestParam(value="userId") Integer userId, @RequestParam(value="password") String password,
  51.  
    @RequestParam(value="newPassword") String newPassword){
  52.  
    if(userId <= 0 || userId > 2){
  53.  
    return "未知的用戶";
  54.  
    }
  55.  
    if(StringUtils.isEmpty(password) || StringUtils.isEmpty(newPassword)){
  56.  
    return "密碼不能爲空";
  57.  
    }
  58.  
    if(password.equals(newPassword)){
  59.  
    return "新舊密碼不能相同";
  60.  
    }
  61.  
    return "密碼修改爲功!";
  62.  
    }
  63.  
    }

完成上述代碼添加上,啓動Spring Boot程序,訪問:http://localhost:8080/swagger-ui.html

如上圖,能夠看到暴漏出來的控制器信息,點擊進入能夠看到詳細信息。

兩個注意點:

1.  paramType會直接影響程序的運行期,若是paramType與方法參數獲取使用的註解不一致,會直接影響到參數的接收。

例如:

使用Sawgger UI進行測試,接收不到!

2.  還有一個須要注意的地方:

Conntroller中定義的方法必須在@RequestMapper中顯示的指定RequestMethod類型,不然SawggerUi會默認爲全類型皆可訪問, API列表中會生成多條項目。

如上圖:updatePassword()未指定requestMethod,結果生成了7條API信息。因此若是沒有特殊需求,建議根據實際狀況加上requestMethod。

 

5:Swagger UI面板說明

6:參考

http://blog.didispace.com/springbootswagger2/

http://blog.csdn.net/jia20003/article/details/50700736

Swagger官網 :http://swagger.io/

Spring Boot & Swagger UI : http://fruzenshtein.com/spring-boot-swagger-ui/

Github:https://github.com/swagger-api/swagger-core/wiki/Annotations

 

---------------------------------------------------------------------------------------

7:接收對象傳參的例子

在POJO上增長

  1.  
    package com.zhongying.api.model.base;
  2.  
     
  3.  
    import io.swagger.annotations.ApiModel;
  4.  
    import io.swagger.annotations.ApiModelProperty;
  5.  
     
  6.  
    /**
  7.  
    * 醫生對象模型,不要使用該類
  8.  
    * @author SUNF
  9.  
    *
  10.  
    */
  11.  
    @ApiModel(value="醫生對象模型")
  12.  
    public class DemoDoctor{
  13.  
    @ApiModelProperty(value="id" ,required=true)
  14.  
    private Integer id;
  15.  
    @ApiModelProperty(value="醫生姓名" ,required=true)
  16.  
    private String name;
  17.  
     
  18.  
     
  19.  
    public Integer getId() {
  20.  
    return id;
  21.  
    }
  22.  
     
  23.  
    public void setId(Integer id) {
  24.  
    this.id = id;
  25.  
    }
  26.  
     
  27.  
    public String getName() {
  28.  
    return name;
  29.  
    }
  30.  
     
  31.  
    public void setName(String name) {
  32.  
    this.name = name;
  33.  
    }
  34.  
     
  35.  
    @Override
  36.  
    public String toString() {
  37.  
    return "DemoDoctor [id=" + id + ", name=" + name + "]";
  38.  
    }
  39.  
     
  40.  
    }
  41.  
     

注意: 在後臺採用對象接收參數時,Swagger自帶的工具採用的是JSON傳參,    測試時須要在參數上加入@RequestBody,正常運行採用form或URL提交時候請刪除。 

  1.  
    package com.zhongying.api.controller.app;
  2.  
     
  3.  
    import java.util.ArrayList;
  4.  
    import java.util.List;
  5.  
     
  6.  
    import javax.servlet.http.HttpServletRequest;
  7.  
     
  8.  
    import org.springframework.stereotype.Controller;
  9.  
    import org.springframework.web.bind.annotation.RequestBody;
  10.  
    import org.springframework.web.bind.annotation.RequestMapping;
  11.  
    import org.springframework.web.bind.annotation.RequestMethod;
  12.  
    import org.springframework.web.bind.annotation.RequestParam;
  13.  
    import org.springframework.web.bind.annotation.ResponseBody;
  14.  
     
  15.  
    import com.github.pagehelper.PageInfo;
  16.  
    import com.zhongying.api.exception.HttpStatus401Exception;
  17.  
    import com.zhongying.api.model.base.DemoDoctor;
  18.  
     
  19.  
    import io.swagger.annotations.Api;
  20.  
    import io.swagger.annotations.ApiImplicitParam;
  21.  
    import io.swagger.annotations.ApiImplicitParams;
  22.  
    import io.swagger.annotations.ApiOperation;
  23.  
     
  24.  
    /**
  25.  
    * 醫生類(模擬)
  26.  
    * @author SUNF
  27.  
    */
  28.  
    @RequestMapping("/api/v1")
  29.  
    @Controller
  30.  
    @Api(value = "DoctorTestController-醫生信息接口模擬")
  31.  
    public class DoctorTestController {
  32.  
     
  33.  
    /**
  34.  
    * 添加醫生
  35.  
    *
  36.  
    * 在使用對象封裝參數進行傳參時,須要在該對象添加註解,將其註冊到swagger中
  37.  
    * @link com.zhongying.api.model.base.DemoDoctor
  38.  
    *
  39.  
    * 注意: 在後臺採用對象接收參數時,Swagger自帶的工具採用的是JSON傳參,
  40.  
    * 測試時須要在參數上加入@RequestBody,正常運行採用form或URL提交時候請刪除。
  41.  
    *
  42.  
    * @param doctor 醫生類對象
  43.  
    * @return
  44.  
    * @throws Exception
  45.  
    */
  46.  
    @ResponseBody
  47.  
    @RequestMapping(value="/doctor", method= RequestMethod.POST )
  48.  
    @ApiOperation(value="添加醫生信息", notes="")
  49.  
    public String addDoctor(@RequestBody DemoDoctor doctor) throws Exception{
  50.  
    if(null == doctor || doctor.getId() == null){
  51.  
    throw new HttpStatus401Exception("添加醫生失敗","DT3388","未知緣由","請聯繫管理員");
  52.  
    }
  53.  
    try {
  54.  
    System. out.println("成功----------->"+doctor.getName());
  55.  
    } catch (Exception e) {
  56.  
    throw new HttpStatus401Exception("添加醫生失敗","DT3388","未知緣由","請聯繫管理員");
  57.  
    }
  58.  
     
  59.  
    return doctor.getId().toString();
  60.  
    }
  61.  
     
  62.  
    /**
  63.  
    * 刪除醫生
  64.  
    * @param doctorId 醫生ID
  65.  
    * @return
  66.  
    */
  67.  
    @ResponseBody
  68.  
    @RequestMapping(value="/doctor/{doctorId}", method= RequestMethod.DELETE )
  69.  
    @ApiOperation(value="刪除醫生信息", notes="")
  70.  
    @ApiImplicitParam(paramType="query", name = "doctorId", value = "醫生ID", required = true, dataType = "Integer")
  71.  
    public String deleteDoctor(@RequestParam Integer doctorId){
  72.  
    if(doctorId > 2){
  73.  
    return "刪除失敗";
  74.  
    }
  75.  
    return "刪除成功";
  76.  
    }
  77.  
     
  78.  
    /**
  79.  
    * 修改醫生信息
  80.  
    * @param doctorId 醫生ID
  81.  
    * @param doctor 醫生信息
  82.  
    * @return
  83.  
    * @throws HttpStatus401Exception
  84.  
    */
  85.  
    @ResponseBody
  86.  
    @RequestMapping(value="/doctor/{doctorId}", method= RequestMethod.POST )
  87.  
    @ApiOperation(value="修改醫生信息", notes="")
  88.  
    @ApiImplicitParam(paramType="query", name = "doctorId", value = "醫生ID", required = true, dataType = "Integer")
  89.  
    public String updateDoctor(@RequestParam Integer doctorId, @RequestBody DemoDoctor doctor) throws HttpStatus401Exception{
  90.  
    if(null == doctorId || null == doctor){
  91.  
    throw new HttpStatus401Exception("修改醫生信息失敗","DT3391","id不能爲空","請修改");
  92.  
    }
  93.  
    if(doctorId > 5 ){
  94.  
    throw new HttpStatus401Exception("醫生不存在","DT3392","錯誤的ID","請更換ID");
  95.  
    }
  96.  
    System. out.println(doctorId);
  97.  
    System. out.println(doctor);
  98.  
    return "修改爲功";
  99.  
    }
  100.  
     
  101.  
    /**
  102.  
    * 獲取醫生詳細信息
  103.  
    * @param doctorId 醫生ID
  104.  
    * @return
  105.  
    * @throws HttpStatus401Exception
  106.  
    */
  107.  
    @ResponseBody
  108.  
    @RequestMapping(value="/doctor/{doctorId}", method= RequestMethod.GET )
  109.  
    @ApiOperation(value="獲取醫生詳細信息", notes="僅返回姓名..")
  110.  
    @ApiImplicitParam(paramType="query", name = "doctorId", value = "醫生ID", required = true, dataType = "Integer")
  111.  
    public DemoDoctor getDoctorDetail(@RequestParam Integer doctorId) throws HttpStatus401Exception{
  112.  
    System. out.println(doctorId);
  113.  
    if(null == doctorId){
  114.  
    throw new HttpStatus401Exception("查看醫生信息失敗","DT3390","未知緣由","請聯繫管理員");
  115.  
    }
  116.  
    if(doctorId > 3){
  117.  
    throw new HttpStatus401Exception("醫生不存在","DT3392","錯誤的ID","請更換ID");
  118.  
    }
  119.  
    DemoDoctor doctor = new DemoDoctor();
  120.  
    doctor.setId( 1);
  121.  
    doctor.setName( "測試員");
  122.  
    return doctor;
  123.  
    }
  124.  
     
  125.  
    /**
  126.  
    * 獲取醫生列表
  127.  
    * @param pageIndex 當前頁數
  128.  
    * @param pageSize 每頁記錄數
  129.  
    * @param request
  130.  
    * @return
  131.  
    * @throws HttpStatus401Exception
  132.  
    */
  133.  
    @ResponseBody
  134.  
    @RequestMapping(value="/doctor", method= RequestMethod.GET )
  135.  
    @ApiOperation(value="獲取醫生列表", notes="目前一次所有取,不分頁")
  136.  
    @ApiImplicitParams({
  137.  
    @ApiImplicitParam(paramType="header", name = "token", value = "token", required = true, dataType = "String"),
  138.  
    @ApiImplicitParam(paramType="query", name = "pageIndex", value = "當前頁數", required = false, dataType = "String"),
  139.  
    @ApiImplicitParam(paramType="query", name = "pageSize", value = "每頁記錄數", required = true, dataType = "String"),
  140.  
    })
  141.  
    public PageInfo<DemoDoctor> getDoctorList(@RequestParam(value = "pageIndex", required = false, defaultValue = "1") Integer pageIndex,
  142.  
    @RequestParam(value = "pageSize", required = false) Integer pageSize,
  143.  
    HttpServletRequest request) throws HttpStatus401Exception{
  144.  
     
  145.  
    String token = request.getHeader( "token");
  146.  
    if(null == token){
  147.  
    throw new HttpStatus401Exception("沒有權限","SS8888","沒有權限","請查看操做文檔");
  148.  
    }
  149.  
    if(null == pageSize){
  150.  
    throw new HttpStatus401Exception("每頁記錄數不粗安在","DT3399","不存在pageSize","請查看操做文檔");
  151.  
    }
  152.  
     
  153.  
    DemoDoctor doctor1 = new DemoDoctor();
  154.  
    doctor1.setId( 1);
  155.  
    doctor1.setName( "測試員1");
  156.  
    DemoDoctor doctor2 = new DemoDoctor();
  157.  
    doctor2.setId( 2);
  158.  
    doctor2.setName( "測試員2");
  159.  
     
  160.  
    List<DemoDoctor> doctorList = new ArrayList<DemoDoctor>();
  161.  
    doctorList.add(doctor1);
  162.  
    doctorList.add(doctor2);
  163.  
    return new PageInfo<DemoDoctor>(doctorList);
  164.  
    }
  165.  
     
  166.  
     
  167.  
    }

增長header:

    如今不少請求須要在header增長額外參數,能夠參考getDoctorList()的作法,使用request接收。

 

原文連接:https://blog.csdn.net/sanyaoxu_2/article/details/80555328

相關文章
相關標籤/搜索