一篇文章教你快速上手接口管理工具swagger


一、關於swagger

1、什么是swagger?

swagger是spring fox的一套產品,可以作為后端開發者測試接口的工具,也可以作為前端取數據的接口文檔。

2、為什么使用?

相比於傳統的接口文檔書寫,開發者可以以更高的效率來進行接口測試與開發。而且使得更具可讀性。

3、怎樣配置?

引入依賴

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

配置代碼 

import io.swagger.annotations.ApiOperation;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import springfox.documentation.builders.ApiInfoBuilder;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.service.ApiInfo;
import springfox.documentation.service.Contact;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2;

@Configuration  // 注冊成ioc組件
@EnableSwagger2  //開啟swagger2
public class SwaggerConfig {

   // 掃描所有帶@ApiOperation注解的類
    @Bean
    public Docket api() {
        return new Docket(DocumentationType.SWAGGER_2)
                .apiInfo(apiInfo())
                .select()
                .apis(RequestHandlerSelectors.withMethodAnnotation(ApiOperation.class))
                .build();
    }
    
    //api接口作者相關信息
    private ApiInfo apiInfo() {
        Contact contact = new Contact("與李", "", "1451633962@qq.com");
        ApiInfo apiInfo = new ApiInfoBuilder().license("").title("CSDN").description("接口文檔").contact(contact).version("3.0").build();
        return apiInfo;
    }
}

二、使用教程

@Api :對rest接口類的注解

--value 對資源的標簽名

--description 描述

@ApiOperation :對方法的注解

--value 對資源的標簽名

--notes 對方法操作的描述

@ApiImplicitParams :對多個參數的描述的集合

@ApiImplicitParam:在@ApiImplicitParams里面

--name 屬性字段名

--value 屬性字段含義

--required 是否必填(true/false)

--paramType 參數位置("query"為參數放置url,"body"為post方法放在body里...)

--dataType 參數類型("String"、"int"...)

@ApiModel :對實體類的描述

@ApiModelProperty :對實體字段的描述

--name 屬性名稱

--value 屬性描述

--hidden 是否不再swagger頁面展示(true/false)

三、踩過的坑

1、swagger-ui頁面卡死

原因:返回的實體或者入參實體中字段重復嵌套,導致swagger頁面在展示model時需要大量循環計算,導致cpu占滿,瀏覽器資源耗盡導致頁面卡死。

解決方案:

方案1、注意實體中字段的數據的嵌套,隱藏改字段或者修改實體,避免嵌套。

方案2、不用swagger,用其他接口測試工具(0_0)

2、POST請求時,Data Type未顯示字段注釋

 解決方案:

給請求實體加上@RequestBody注解


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM