Springboot系列(七) 集成接口文檔swagger,使用,測試

Springboot 配置接口文檔swagger

往期推薦html

SpringBoot系列(一)idea新建Springboot項目前端

SpringBoot系列(二)入門知識java

springBoot系列(三)配置文件詳解web

SpringBoot系列(四)web靜態資源配置詳解spring

SpringBoot系列(五)Mybatis整合完整詳細版json

SpringBoot系列(六)集成thymeleaf詳解版後端

本文目錄api

1. swagger2 介紹

1.1 簡介數組

 Swagger 是一個規範和完整的框架,用於生成、描述、調用和可視化 RESTful 風格的 Web 服務。整體目標是使客戶端和文件系統做爲服務器以一樣的速度來更新。瀏覽器

 隨着先後端技術的日漸成熟,先後端的交互就只有接口了,前端請求接口獲取數據,因此接口的格式化也就至關重要,有一個標準格式的接口文檔在開發過程當中是至關重要的,swagger就是這麼一個在線的接口文檔,在SpringBoot的集成之中也至關便利。

swagger能夠自動生成在線接口文檔,界面可視化的同時保證了便利的測試接口。

2. maven 配置swagger2依賴

 建立一個SpringBoot web 項目,而後在pom.xml中添加以下依賴:

<dependency>
    <groupId>io.springfox</groupId>
    <artifactId>springfox-swagger2</artifactId>
    <version>2.9.2</version>
</dependency>
<dependency>
    <groupId>io.springfox</groupId>
    <artifactId>springfox-swagger-ui</artifactId>
    <version>2.9.2</version>
</dependency>

 能夠根據本身的SringBoot版本適當下降swagger2 的版本。

3. swagger2 配置

 在Springboot啓動類的同級目錄下面建立一個config的包,而後建立一個配置Swagger2 的配置類。

package com.example.demoswagger.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
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;

/** 
 * @author 全棧學習筆記
 * @date 2020/4/19 16:00
 * @description
 */
@Configuration
@EnableSwagger2
public class SwaggerConfig {
    @Bean
    public Docket createRestApi() {
        return new Docket(DocumentationType.SWAGGER_2)
                // 指定構建api文檔的詳細信息的方法:apiInfo()
                .apiInfo(apiInfo())
                .select()
                // 指定要生成api接口的包路徑
                .apis(RequestHandlerSelectors.basePackage("com.example.demoswagger.controller"))
                //使用了 @ApiOperation 註解的方法生成api接口文檔
                //.apis(RequestHandlerSelectors.withMethodAnnotation(ApiOperation.class))
                .paths(PathSelectors.any())
                //能夠根據url路徑設置哪些請求加入文檔,忽略哪些請求
                .build();
    }

    /**
     * 設置api文檔的詳細信息
     */
    private ApiInfo apiInfo() {
        return new ApiInfoBuilder()
                // 標題
                .title("Spring Boot集成Swagger2")
                // 接口描述
                .description("swagger")
                // 聯繫方式
                .contact("微信公衆號"+"全棧學習筆記"+"359076197@qq.com")
                // 版本信息
                .version("1.0")
                // 構建
                .build();
    }
}

注意其中的包,不要導錯包了。

配置代碼說明:

 1. 使用 @Configuration 註解,標識這是一個配置類,項目啓動的時候會自動調用加載,@EnableSwagger2 註解的做用是自動開啓swagger2。

 2. apiInfo() 方法裏面的參數能夠本身設定,在第一個方法中,咱們除了能夠根據接口所在的包對應生成接口文檔還能夠根據項目中是否有方法使用了 @ApiOperation註解來判斷是否生成api文檔。

4. controller 測試編寫以及註解說明

 上面咱們配置好了swagger api生成的配置以後就能夠編寫測試的controller,建立一個與config同級的包controller,而後裏面寫一個TestController

單個參數

@RestController
@RequestMapping("/Test")
@Api("測試swagger接口")
public class TestController {

    @RequestMapping(path = "/getStudent",method = RequestMethod.GET)
    @ApiOperation("/根據學生id獲取學生信息")
    @ApiImplicitParam(name = "id",value = "id",required = true,paramType = "query",dataType = "int")
    public Student getStudent(@RequestParam Integer id){
        Student student = new Student();
        student.setId(11);
        student.setAge(21);
        student.setName("全棧學習筆記");
        Map<Integer,Student> studentMap = new HashMap<>();
        studentMap.put(11,student);
        return studentMap.get(id);
    }
}

 其中,Student類等會會貼出來。

代碼說明:

  1. @RestController 至關於@Controller+@ResponseBody 註解,讓標識的這個類返回json格式的數據。
  2. 上面加上@Api的註解,說明這個類要生成api文檔,並給予描述。至關於能夠根據這個類做爲類別的劃分。在類裏面的方法加上@ApiOperation 註解 用來描述這個方法(接口)是用來幹嗎的;
  3. @ApiImplicitParam 註解是爲了描述這個方法之中的參數。其中的name,value屬性你應該知道。required 屬性是標識在測試接口時,這個參數是否須要傳,true爲必須傳,false爲非必須。
  4. @ApiImplicitParam之中的paramType是標識這個參數應該在哪去獲取,經常使用的有如下幾種
  • header-->放在請求頭。請求參數的獲取註解:@RequestHeader
  • query -->經常使用於get請求的參數拼接。請求參數的獲取註解:@RequestParam
  • path -->(用於restful接口)-->請求參數的獲取獲取註解:@PathVariable
  • body -->放在請求體。請求參數的獲取註解:@RequestBody
  1. @ApiImplicitParam之中的dataType 是用來標識這個參數的類型,默認爲String,若是是數組類型,須要加上allowMultiple=true,表示是數組類型的數據。也能夠是自定義的對象類型。

多個參數的用法

@RequestMapping(path = "/getStudent",method = RequestMethod.PATCH)
@ApiOperation("/根據學生id獲取學生信息")
@ApiImplicitParams({
    @ApiImplicitParam(name = "name",value = "姓名",required = true,paramType = "query",dataType = "String"),
    @ApiImplicitParam(name = "age",value = "年齡",required = true,paramType = "query",dataType = "int")
})
public Student editStudent(@RequestParam String name, @RequestParam Integer age){
    Student student = new Student();
    student.setId(12);
    student.setName(name);
    student.setAge(age);
    return student;

}

 須要對多個參數進行屬性說明時,須要用到 @ApiImplicitParams,而後裏面再用 @ApiImplicitParam

參數是對象的用法

controller代碼

@ApiOperation("/添加學生信息")
    @RequestMapping(path = "/addStudent",method = RequestMethod.POST)
    public Map<Integer,Student> AddStudent(@RequestBody Student student){
        Map<Integer,Student> studentMap = new HashMap<>();
        studentMap.put(student.getId(),student);
        return studentMap;
    }

entity代碼:

/**
 * (Student)實體類
 *
 * @author 微信公衆號:全棧學習筆記
 * @since 2020-04-14 11:39:10
 */
@ApiModel("學生類")
public class Student {

    /**
    * 惟一標識id
    */
    @ApiModelProperty("id")
    private Integer id;
    /**
    * 姓名
    */
    @ApiModelProperty("姓名")
    private String name;
    /**
    * 年齡
    */
    @ApiModelProperty(value = "年齡")
    private Integer age;
}
&emsp;省略get,set方法
&emsp;@ApiModelProperty 的屬性配置相對以前那個@ApiImplicitParam的屬性更多更全。

5. 接口測試

 完成以上步驟,帶大家看看swagger的界面如何,啓動項目,瀏覽器輸入localhost:8091/swagger-ui.html
以下:

 打開以後

 測試一個接口

 結果返回

6.總結

 本期的分享就到這裏,文中講解了swagger2的配置,用法,以及測試,整個流程都講解的較詳細。若是你以爲文章有用,點個贊吧!

相關文章
相關標籤/搜索