網上的教程我覺得看的不舒服,所以自己寫了一篇,爲學習設計出優雅的後端代碼做前期學習鋪墊。
Swagger是什麼
Swagger是一個規範和完整的框架,用於生成、描述、調用和可視化 RESTful 風格的 Web 服務。總體目標是使客戶端和文件系統作爲服務器以同樣的速度來更新。文件的方法,參數和模型緊密集成到服務器端的代碼,允許API來始終保持同步。
在項目開發中,根據業務代碼自動生成API文檔,給前端提供在線測試,自動顯示JSON格式,方便了後端與前端的溝通與調試成本。
Swagger有一個缺點就是侵入性模式,必須配置在具體的代碼裏。
新建 springboot 工程 找到 pom.xml
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger2</artifactId>
<version>2.2.4</version>
</dependency>
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger-ui</artifactId>
<version>2.2.4</version>
</dependency>
原本我使用的是 2.2.2 版本突然就報錯了
ERROR:o.s.b.d.LoggingFailureAnalysisReporter
換成 2.2.4 就 ok 了。所以有時候報錯可能是版本問題。
第一個是API獲取的包
第二是官方給出的一個ui界面,這個界面可以自定義,默認是官方的
新建 swaggerConfig.java 配置 Swagegr 的基本配置信息
com.example.demo.config.SwaggerConfig
package com.example.demo.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;
@Configuration
@EnableSwagger2
public class SwaggerConfig {
// 在 apiInfo 中使用
private ApiInfo apiInfo() {
return new ApiInfoBuilder().title("API 接口文檔")
.description("這裏是描述信息")
.version("1.1.0")
.build();
}
// 註冊爲 spring 的 bean
@Bean
public Docket createRestApi(){
return new Docket(DocumentationType.SWAGGER_2)
.apiInfo(apiInfo())
.select()
.apis(RequestHandlerSelectors.basePackage("com.example.demo.controller")) // 這裏指定 API 接口包位置
.paths(PathSelectors.any())
.build();
}
}
啓動 springboot 項目,就可以訪問頁面了
輸入 http://localhost:8080/swagger-ui.html
… 待續