1. 程式人生 > 程式設計 >IDEA SpringBoot 專案配置Swagger2的詳細教程

IDEA SpringBoot 專案配置Swagger2的詳細教程

  • 原先前後端分離的api文件開啟了前後端相互撕逼的對接之路
  • api更新不及時導致對接失敗,以及存在測試不夠方便,而swagger則很好的解決了這個問題

在專案中也經常用到swagger2,於是動手記錄一下swagger2配置過程,希望能帶來一點幫助。

在SpringBoot專案當中使用Swagger主要分為以下幾步:

1、SpringBoot-web專案並新增pom.xml依賴

2、編寫HelloController,測試成功執行

3、建立一個SwaggerConfig類,配置swagger-ui

流程確實是很簡單的,但是能真正的在專案中活用swagger卻不是那麼簡單

1、SpringBoot-web專案並新增pom.xml依賴

可以直接在maven repository搜尋

多最一句,一般在選擇maven依賴時,我們趨向於選擇最穩定版本,可以通過Usages判斷,儘量不要選擇最新版,及時並沒有什麼影響。詳細經歷過版本衝突和版本不相容的小夥伴應該深有體會。

在這裡插入圖片描述

<!-- https://mvnrepository.com/artifact/io.springfox/springfox-swagger2 -->
<dependency>
  <groupId>io.springfox</groupId>
  <artifactId>springfox-swagger2</artifactId>
  <version>2.9.2</version>
</dependency>
<!-- 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>

2、編寫HelloController,測試成功執行

package cn.swpu.myblog.controller;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

@Controller
@Api(tags = "測試-HelloWorld") //這個controller下的所有介面的描述
public class HelloController {

  @ApiOperation("測試Swagger2") //顯示在介面的資訊說明
  @RequestMapping(value = "/test",method = RequestMethod.GET) //請求路徑和型別
  public void testSwagger(){

  }
}

3、建立一個SwaggerConfig類,配置swagger-ui

package cn.swpu.myblog.config;

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

@Configuration
@EnableSwagger2
public class SwaggerConfig {
}

然後就可以根據你的埠訪問swagger-ui了,例如我的是8099

http://localhost:8099/swagger-ui.html#/

在這裡插入圖片描述
在這裡插入圖片描述

至此IDEA 繼承Swagger就可以了,但這僅僅只是個開始,swagger還是有很多的實用技巧。

到此這篇關於IDEA SpringBoot 專案配置Swagger2的詳細教程的文章就介紹到這了,更多相關IDEA SpringBoot 專案配置Swagger2內容請搜尋我們以前的文章或繼續瀏覽下面的相關文章希望大家以後多多支援我們!