天天看點

Springboot 內建 Swagger2使用

文章目錄

      • WHAT
      • WHY
      • HOW

WHAT

背景服務接口文檔

WHY

  1. 可以直接在編寫代碼的時候,順便把接口文檔寫了。
  2. 便于測試接口

HOW

  1. 導包
<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>
           
  1. 配置檔案
package com.komlin.user.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;

/**
 * @Auther: albert
 * @Date: 2019-03-06 09:44
 * @Description:
 */
@Configuration
//開啟Swagger
@EnableSwagger2
public class Swagger2 {

    @Bean
    public Docket createRestApi() {
        return new Docket(DocumentationType.SWAGGER_2)
                .apiInfo(apiInfo())
                .select()
                .apis(RequestHandlerSelectors.basePackage("com.komlin"))
                .paths(PathSelectors.any())
                .build();
    }

    private ApiInfo apiInfo() {
        return new ApiInfoBuilder()
                .title("使用者服務")
                .description("關于使用者服務接口文檔")
                .termsOfServiceUrl("http://127.0.0.1/api/user-service/")
                .version("1.0")
                .build();
    }
}

           
  1. 接口通過注解編寫

    @Api():作用于類上,表示這個類是swagger的資源。

    tags = ”說明該類的作用“

    @ApiOperation():用在請求的方法上,說明的方法的使用者和作用

    value=“說明方法的用途、作用”

    notes="方法的備注說明“

    @ApiImplicitParams():用在請求的方法上,表示一組參數說明,可以包含多個@ApiImplicitParam()

    @ApiImplicitParam():指定一個請求參數的各個方面

    name:參數名

    value:參數的漢字說明

    required:參數是否必須傳

    dataType:參數類型

    defaultValue:參數的預設值

    @ApiResponses():用在請求的方法上,表示一組響應。可以包含多個@ApiResponse()

    @ApiResponse():用于表示一個錯誤的響應資訊

    code:數字

    message:資訊

    response:抛出異常的類

    @ApiModel():用在響應類上,表示一個傳回響應資料的資訊。

    @ApiModelProperty():用在屬性上,描述響應類的屬性

  2. 檢視接口文檔

    輸入http:port/swagger-ui.html

    Springboot 內建 Swagger2使用