SpringBoot-Swagger

Swagger

1. 簡介

  • 號稱世界上最流行的API框架
  • RestFul API 文檔在線自動生成工具 => API文檔與API定義同步更新
  • 直接運行, 能夠在線測試API接口
  • 支持多種語言
  • 在項目中使用Swagger須要SpringFox
    • Swagger2
    • ui

2. SpringBoot集成Swagger

1. 導入依賴

Swagger3.0直接導入Springfox Boot Starter就能夠了html

<!-- https://mvnrepository.com/artifact/io.springfox/springfox-boot-starter -->
<dependency>
    <groupId>io.springfox</groupId>
    <artifactId>springfox-boot-starter</artifactId>
    <version>3.0.0</version>
</dependency>

2.X版本須要導入Swagger2.0和UIjava

<!-- https://mvnrepository.com/artifact/io.springfox/springfox-swagger-ui -->
<dependency>
    <groupId>io.springfox</groupId>
    <artifactId>springfox-swagger-ui</artifactId>
    <version>2.9.2</version>
</dependency>

<!-- https://mvnrepository.com/artifact/io.springfox/springfox-swagger2 -->
<dependency>
    <groupId>io.springfox</groupId>
    <artifactId>springfox-swagger2</artifactId>
    <version>2.9.2</version>
</dependency>

咱們這裏仍是使用2.X版本web

2. 配置Swagger

package com.wang.config;

import org.springframework.context.annotation.Configuration;
import springfox.documentation.swagger2.annotations.EnableSwagger2;

@Configuration
//開啓Swagger2
@EnableSwagger2
public class SwaggerConfig {
    
}

注意spring

  • 只要在Swagger配置類上加上@EnableSwagger2註解, 就可使用Swagger2了
  • Swagger的地址爲http://localhost:8080/swagger-ui.html

3. Swagger配置

1. 配置Swagger信息

Swagger的Bean實例 ==> Docketapache

package com.wang.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import springfox.documentation.service.ApiInfo;
import springfox.documentation.service.Contact;
import springfox.documentation.service.VendorExtension;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2;

import java.util.ArrayList;

@Configuration
//開啓Swagger2
@EnableSwagger2
public class SwaggerConfig {

    //配置了Swagger的Docket的Bean實例
    @Bean
    public Docket docket() {
        return new Docket(DocumentationType.SWAGGER_2)
                .apiInfo(apiInfo());
    }

    //配置Swagger信息 apiInfo
    private ApiInfo apiInfo() {
        //做者信息
        Contact contact = new Contact("wang", "https://www.cnblogs.com/wang-sky/", "715180879@qq.com");

        return new ApiInfo(
                "個人Swagger接口文檔",
                "這是一個Swagger接口文檔",
                "V 1.0",
                "https://www.cnblogs.com/wang-sky/",
                contact,
                "Apache 2.0",
                "http://www.apache.org/licenses/LICENSE-2.0",
                new ArrayList<VendorExtension>());
    }


}

這裏修改的是Swagger頁面的一些信息, 結果以下編程

image-20200925141343307

注意api

  • Docket不要忘了註冊Bean並返回一個new Docket
  • 返回的Docket要傳入一個參數指定產生的文檔的類型, 咱們這裏使用 DocumentationType.SWAGGER_2

2. Swagger配置掃描接口

Docket.select()瀏覽器

@Bean
public Docket docket() {
    //RequestHandlerSelectors 配置要掃描接口的方式
    /*
    basePackage     指定要掃描的包
    any             掃描所有
    none            都不掃描
    withClassAnnotation 掃描類上的註解,參數是一個註解的反射對象, 好比 withClassAnnotation(RestController.class)
    withMethodAnnotation    掃描方法上的註解
     */
    //paths 過濾的路徑, 須要傳入PathSelectors.xxx 選擇過濾的方式
    return new Docket(DocumentationType.SWAGGER_2)
            .apiInfo(apiInfo())
            .select()
            .apis(RequestHandlerSelectors.basePackage("com.wang.controller"))
            .paths(PathSelectors.ant("/wang/**"))
            .build();
}

注意安全

  • apis 掃描, 要傳入RequestHandlerSelectors.xxx 指定掃描的方式
    • basePackage 指定要掃描的包
    • any 掃描所有
    • none 都不掃描
    • withClassAnnotation 掃描類上的註解,參數是一個註解的反射對象, 好比 withClassAnnotation(RestController.class)
    • withMethodAnnotation 掃描方法上的註解
  • paths 過濾的路徑, 須要傳入PathSelectors.xxx 選擇過濾的方式
  • 最後要.build(), 建造者模式, 同時因爲這是鏈式編程, 必定要寫!
  • select().XXX.XXX...bulid()是一套, 中間能夠寫的方法是肯定的, 不能亂寫

3. 配置Swagger是否啓動

只在生產環境下使用Swagger, 而在發佈的時候不使用的方法springboot

分別創建不一樣環境的yml

image-20200925150147345

在application中選擇啓動的環境, 這裏選擇生產環境

spring:
  profiles:
    active: dev

配置Swagger

//配置了Swagger的Docket的Bean實例
@Bean
public Docket docket(Environment environment) {
    //RequestHandlerSelectors 配置要掃描接口的方式
    /*
    basePackage     指定要掃描的包
    any             掃描所有
    none            都不掃描
    withClassAnnotation 掃描類上的註解,參數是一個註解的反射對象, 好比 withClassAnnotation(RestController.class)
    withMethodAnnotation    掃描方法上的註解
     */
    //paths 過濾的路徑, 須要傳入PathSelectors.xxx 選擇過濾的方式

    //設置要顯示的Swagger環境
    Profiles profiles = Profiles.of("dev");

    //經過environment.acceptsProfiles, 判斷是否處在本身設定的環境當中
    boolean flag = environment.acceptsProfiles(profiles);

    return new Docket(DocumentationType.SWAGGER_2)
            .apiInfo(apiInfo())
            .select()
            .apis(RequestHandlerSelectors.basePackage("com.wang.controller"))
            .paths(PathSelectors.ant("/wang/**"))
            .build()
            .enable(flag);
}

注意

  • .enable
  • 只能在select().XXX.XXX....bulid() 外面寫
  • 默認爲true, 若是爲False, 則Swagger不能在瀏覽器中訪問
  • 要用 Profiles profiles = Profiles.of("dev"); 指定激活的環境的名字
  • 得到當前的生產環境(application指定的環境), 要給Docket傳入一個Environment對象, 其中保存了當前環境的名字
  • environment.acceptsProfiles(profiles); 利用此方法得到是否在給定環境的布爾值

4. 配置API文檔的分組

.groupName("個人API")

配置多個分組, 只須要配置多個Docket便可

4. 實體類配置

1. 實體類的註解

package com.wang.pojo;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;

@Data
//@Api("註釋")
@ApiModel("用戶實體類")
public class User {

    @ApiModelProperty("用戶名")
    private String username;
    @ApiModelProperty("密碼")
    private String password;
}

@ApiModel或者@Api在類上

@ApiModelProperty在屬性上

屬性爲私有, 要寫getter才能取到屬性名

結果顯示在Model上

image-20200925162237381

2. 接口類的註解

package com.wang.controller;

import com.wang.pojo.User;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class HelloController {

    @GetMapping(value = "/hello")
    public String hello() {
        return "Hello!";
    }

    //只要咱們的接口中, 返回值中存在實體類, 他就會被掃描到Swagger中
    @PostMapping("/user")
    public User user() {
        return new User();
    }

    //Operation接口
    //Get請求中, 若是添加了字段的註釋@ApiParam, Swagger沒法測試
    @ApiOperation("Hello2接口")
    @GetMapping("/hello2")
    public String hello2(String username) {
        return "hello " + username;
    }

    //Operation接口
    @ApiOperation("Hello3接口")
    @PostMapping("/hello3")
    public User hello3(@ApiParam("用戶") User user) {
        return user;
    }
}

注意

  • 只要咱們的接口中, 返回值中存在實體類或者字符串, 他就會被掃描到Swagger中
  • @ApiOperation 方法的註釋
  • @ApiParm 參數的註釋
  • Get請求中, 若是添加了字段的註釋@ApiParam, Swagger沒法測試

5. 總結

  • 咱們能夠經過Swagger給一些比較難理解的屬性或者接口, 增長註釋信息
  • 接口文檔實時更新
  • 能夠在線測試
  • 注意, 在正式發佈的時候, 關閉Swagger(出於安全考慮, 並且節省運行內存)
相關文章
相關標籤/搜索