SpringBoot系列(七) 配置接口文檔swagger,詳細流程

Springboot 配置接口文檔swagger

往期推薦

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

SpringBoot系列(二)入門知識

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

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

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

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

本文目錄

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("微信公衆號"+"全棧學習筆記"+"[email protected]")
                // 版本信息
                .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的配置,用法,以及測試,整個流程都講解的較詳細。如果你覺得文章有用,點個贊吧!

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章