天天看點

springboot項目整合Swagger2項目整合 swagger源碼解析Swagger JSON Doc

項目整合 swagger

在聚合工程中的父 pom 工程的 pom 檔案中添加依賴

<!-- swagger2 配置 -->
<dependency>
    <groupId>io.springfox</groupId>
    <artifactId>springfox-swagger2</artifactId>
    <version>2.4.0</version>
</dependency>
<dependency>
    <groupId>io.springfox</groupId>
    <artifactId>springfox-swagger-ui</artifactId>
    <version>2.4.0</version>
</dependency>
<dependency>
    <groupId>com.github.xiaoymin</groupId>
    <artifactId>swagger-bootstrap-ui</artifactId>
    <version>1.6</version>
</dependency>      
  1. 指定API類型為swagger2.0
  2. 定義API文檔彙總資訊
  3. 指定controller包
  4. 所有controller

源碼解析

package springfox.documentation.spi;

import org.springframework.http.MediaType;
import org.springframework.plugin.metadata.SimplePluginMetadata;

public class DocumentationType extends SimplePluginMetadata {
  public static final DocumentationType SWAGGER_12 = 
    new DocumentationType("swagger", "1.2");
  public static final DocumentationType SWAGGER_2 = 
    new DocumentationType("swagger", "2.0");
  public static final DocumentationType SPRING_WEB = 
    new DocumentationType("spring-web", "1.0");
  private final MediaType mediaType;

  /**
   * Creates a new instance of {@code SimplePluginMetadata}.
   */
  public DocumentationType(String name, String version, MediaType mediaType) {
    super(name, version);
    this.mediaType = mediaType;
  }

  public DocumentationType(String name, String version) {
    this(name, version, MediaType.APPLICATION_JSON);
  }

  public MediaType getMediaType() {
    return mediaType;
  }

  @Override
  public boolean equals(Object o) {
    if (this == o) {
      return true;
    }
    if (!(o instanceof DocumentationType)) {
      return false;
    }
    if (!super.equals(o)) {
      return false;
    }

    DocumentationType that = (DocumentationType) o;

    return super.equals(that) && mediaType.equals(that.mediaType);

  }

  @Override
  public int hashCode() {
    int result = super.hashCode();
    result = 31 * result + mediaType.hashCode();
    return result;
  }
}
      

Swagger JSON Doc

  • 線上編輯位址 https://editor.swagger.io/
  • 編輯生成樣闆代碼
  • springboot項目整合Swagger2項目整合 swagger源碼解析Swagger JSON Doc
  • 是以 swagger 不僅支援代碼優先還支援契約優先程式設計。