springboot 集成 swagger 生成後臺接口文檔

之前初步學習了,使用 swagger2 生成 接口文檔,這次我們使用 swagger-spring-boot-starter 來生成接口文檔

Swagger 是一款自動生成在線文檔 + 接口調試的工具。在 WEB 開發中不可否認的是我們需要給客戶端提供 API 接口,這個時候需要藉助 postman 等工具 進行調試,用過這些工具的應該知道一個 POST 請求一堆參數是非常枯燥且煩人的事情,而 swagger 能幫助我們自動生成參數…

swagger-spring-boot-starter 是一款建立在swagger基礎之上的工具包,利用SpringBoot自動裝配的特性,簡化了傳統swagger的繁瑣配置

項目結構

在這裏插入圖片描述

一、引入 pom 文件依賴

<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-web</artifactId>
		</dependency>

		<dependency>
			<groupId>org.projectlombok</groupId>
			<artifactId>lombok</artifactId>
			<optional>true</optional>
		</dependency>

		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-test</artifactId>
			<scope>test</scope>
			<exclusions>
				<exclusion>
					<groupId>org.junit.vintage</groupId>
					<artifactId>junit-vintage-engine</artifactId>
				</exclusion>
			</exclusions>
		</dependency>

		<!-- swagger 支持 springboot 的依賴-->
		<dependency>
			<groupId>com.battcn</groupId>
			<artifactId>swagger-spring-boot-starter</artifactId>
			<version>2.1.2-RELEASE</version>
		</dependency>

二、springboot 中配置 swagger

1、application.yml

spring:
  swagger:
#  開啓 swagger
    enabled: true
#    接口文檔標題
    title:  後臺 API 接口開發文檔
#    描述
    description:  API開發文檔
#    版本
    version: v1.0-beta
    contact:
      name: wxw
#   對後臺接口進行分組
    groups:
      login:
        base-package: com.wxw.springboot_swagger.loginController
        group-name: 登錄模塊
      test:
        base-package: com.wxw.springboot_swagger.testController
        group-name: 測試模塊
      base:
        base-package: com.wxw.springboot_swagger.controller
        group-name: 基礎模塊
#   開啓登錄驗證,並設置用戶名、密碼
    security:
      filter-plugin: true
      username: wxw
      password: 1234

2、controller 接口中

@RestController
@RequestMapping("/test")
@Api(tags = "測試", description = "測試描述", value = "測試")
public class TestController {

    @GetMapping
    @ApiOperation(value = "測試", notes = "測試")
    public String test() {
        return "hello,swagger";
    }
}

三、啓動項目,查看接口文檔

1、查看啓動日誌,可以看到已經加載了 swagger 登錄的 filter

在這裏插入圖片描述

2、訪問: http://localhost:8080/swagger-ui.html#/

輸入配置的用戶名和密碼,有點奇怪的是爲什麼密碼會是明文。。。
在這裏插入圖片描述

3、接口文檔頁面

在這裏插入圖片描述

左側就是 我們在配置文件裏面配置好的分組,右側就是 相關信息

我們可以用這個測試,調用我們寫好的接口
在這裏插入圖片描述

還有更多功能就需要深入研究了
https://github.com/battcn/swagger-spring-boot

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章