1. 程式人生 > 其它 >springboot-swagger:介紹和整合

springboot-swagger:介紹和整合

1 swagger介紹

1.1 前後端分離:

  • 前端 -> 前端控制層、檢視層
  • 後端 -> 後端控制層、服務層、資料訪問層
  • 前後端通過API進行互動
  • 前後端相對獨立且鬆耦合

1.2 產生的問題

  • 前後端整合,前端或者後端無法做到“及時協商,儘早解決”,最終導致問題集中爆發

1.3 解決思路

  • 首先定義schema [ 計劃的提綱 ],並實時跟蹤最新的API,降低整合風險

1.4 使用swagger解決

  • 號稱世界上最流行的API框架
  • Restful Api 文件線上自動生成器 => API 文件 與API 定義同步更新
  • 直接執行,線上測試API
  • 支援多種語言 (如:Java,PHP等)
  • 官網:https://swagger.io/

2 springboot整合swagger

2.1 建立一個springboot專案

參考地址:springboot-hello world

建立過程中引入web模組

2.2 匯入依賴

pom.xml

<!--Springfox-swagger2-->
<dependency>
    <groupId>io.springfox</groupId>
    <artifactId>springfox-swagger2</artifactId>
    <version>3.0.0</version>
</dependency>
<!--swagger-springmvc-->
<dependency>
    <groupId>io.springfox</groupId>
    <artifactId>springfox-swagger-ui</artifactId>
    <version>3.0.0</version>
</dependency>
<!--啟動器-->
<dependency>
    <groupId>io.springfox</groupId>
    <artifactId>springfox-boot-starter</artifactId>
    <version>3.0.0</version>
</dependency>

2.2 建立一個config包,並在該包下編寫swagger的配置類

src/main/java/com/lv/config/SwaggerConfig.java

package com.lv.config;

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

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

}

2.3 在專案的主啟動類上新增@EnableWebMvc註解

如果不進行這一步,專案啟動時會報空指標異常

src/main/java/com/lv/SwaggerDemoApplication.java

package com.lv;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;

@SpringBootApplication
@EnableWebMvc
public class SwaggerDemoApplication {
    public static void main(String[] args) {
        SpringApplication.run(SwaggerDemoApplication.class, args);
    }
}

2.4 啟動專案訪問: http://localhost:8080/swagger-ui/index.html

訪問成功,說明springboot成功整合swagger