天天看點

SpringBoot內建Swagger生成API文檔

  • 本文主要介紹基于springboot架構下使用swagger生成api文檔的基本使用方法
  • 基于REST風格的接口接口規範來進行代碼編寫,加上自動化的api文檔簡直不要太舒服,下面是基本的使用,以及解釋
  • 在傳統開發中我們經常使用word來進行接口文檔的編寫,這種方法很繁瑣,随着時間的增加接口的變化和繁多也會導緻文檔變得難以維護和停止維護,這對于剛入職公司的新人來說是非常的不友好的,swagger可以根據你接口的參數變化随着你伺服器的啟動來進行不斷的更新文檔;
  • 首先需要搭建一個springboot的項目,此處省略;
  • pom依賴
<!--swagger-->
<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>
           
  • swagger的配置相當簡單,需要作為一個配置類來進行加載,以下為代碼
package com.sunyw.xyz.statics;

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.spi.DocumentationType;
import springfox.documentation.swagger2.annotations.EnableSwagger2;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.builders.PathSelectors;
/**
 * @description:swaggerAPI文檔配置屬性類
 * @author: sunyw
 * @time: 2020-02-25 13:13
 */
@Configuration
@EnableSwagger2
public class WeatherSwagger {
    @Bean
    public Docket createSwagger(){
        return new Docket(DocumentationType.SWAGGER_2)
                .apiInfo(apiInfo())
                .select()
                .apis(RequestHandlerSelectors.basePackage("com.sunyw.xyz"))
                .paths(PathSelectors.regex("/api/.*"))
                .build();
    }
    private ApiInfo apiInfo() {
        return new ApiInfoBuilder()
                .title("Weather天氣平台API文檔")
                .description("sunyw")
                .termsOfServiceUrl("https://xxx.xyz")
                .version("1.0")
                .build();
    }
}

           
  • 然後重新啟動項目,通路http://localhost:7000/swagger-ui.html
  • 效果圖
    SpringBoot內建Swagger生成API文檔
  • swagger的測試平台,點開後面的接口即可進行接口測試
    SpringBoot內建Swagger生成API文檔
  • 測試
    SpringBoot內建Swagger生成API文檔
  • 有幫助的話幫忙點個👍