springboot與swagger2的整合

2021-09-05 11:00:24 字數 4260 閱讀 5400

現在測試都提倡自動化測試,那我們作為後台的開發人員,也得進步下啊,以前用postman來測試後台介面,那個麻煩啊,乙個字母輸錯就導致測試失敗,現在swagger的出現可謂是拯救了這些開發人員,便捷之處真的不是一點兩點。下面我們看下如何在微服務中將springboot與swagger來結合吧。

1、swagger是什麼,這個我覺得凡是乙個開發人員就應該知道度娘啊,絕對強大。

簡單說下,它的出現就是為了方便進行測試後台的restful形式的介面,實現動態的更新,當我們在後台的介面修改了後,swagger可以實現自動的更新,而不需要認為的維護這個介面進行測試。

2、springboot與swagger的整合:

第一步:jar包的引入:

關於jar包的引入出現了乙個問題就是版本的問題,可能需要與你的編輯器或者jdk要匹配吧,試了幾個才最終成功匯入jar。

第二步:swagger的配置啟動類編寫:

要使用swagger要進行一些配置,這個在介面的圖上是可以顯示的:類似於說明書:在這個類中我們會使用註解來進行啟動swagger:

具體配置如下:

packagecom.springboot.example;

//swagger2的配置檔案,在專案的啟動類的同級檔案建立

importorg.springframework.context.annotation.bean;

importorg.springframework.context.annotation.configuration;

importspringfox.documentation.builders.apiinfobuilder;

importspringfox.documentation.builders.pathselectors;

importspringfox.documentation.builders.requesthandlerselectors;

importspringfox.documentation.service.apiinfo;

importspringfox.documentation.service.contact;

importspringfox.documentation.spi.documentationtype;

importspringfox.documentation.spring.web.plugins.docket;

importspringfox.documentation.swagger2.annotations.enableswagger2;

@configuration

@enableswagger2

publicclassswagger2

//構建 api文件的詳細資訊函式,注意這裡的註解引用的是哪個

privateapiinfo apiinfo()

}

這裡的坑是:所使用類的引入檔案要注意到底是哪個,之前因為這個出錯了,

@configuration

@enableswagger2

這兩個註解,乙個是swagger2的配置,乙個是專案啟動的時候啟動swagger2.

具體什麼意思看下**就知道了。

//為當前包路徑

.apis(requesthandlerselectors.basepackage("com.springboot.example.controller"))

這個包指的是我們在哪些類中使用swagger2來測試。

第三步:使用swagger來進行模擬測試:

使用swagger2來進行測試介面主要是在哪些類中使用:這裡我們依然選擇在controller層:

packagecom.springboot.example.controller;

importcom.springboot.example.service.studentservice;

importcom.springboot.example.entity.student;

importio.swagger.annotations.api;

importio.swagger.annotations.apiimplicitparam;

importio.swagger.annotations.apioperation;

importorg.slf4j.logger;

importorg.slf4j.logge***ctory;

importorg.springframework.beans.factory.annotation.autowired;

importorg.springframework.web.bind.annotation.pathvariable;

import

importorg.springframework.web.bind.annotation.requestmethod;

importorg.springframework.web.bind.annotation.restcontroller;

/**

* created by administrator on 2017/9/13.

*/

@restcontroller("api")

@api("swaggerdemocontroller相關的api")

上面這些可以看下具體的註解是什麼意思:

這樣swagger2與springboot就整合完畢了。

看下最終效果吧:

訪問路徑:

springboot專案實踐 整合swagger

1.在pom檔案中做如下配置 io.springfoxgroupid springfox swagger2artifactid 2.9.2version dependency io.springfoxgroupid springfox swagger uiartifactid 2.9.2versio...

SpringBoot整合系列 整合Swagger2

io.springfox springfox swagger2 2.7.0 io.springfox springfox swagger ui 2.7.0 一般無配置項,必要時可以新增自定義配置項,在配置類中讀取 swagger2的配置內容僅僅就是需要建立乙個docket例項 configurati...

在springboot專案中使用swaggerui

在pom.xml檔案中配置 用的2.6.1版本,2.9.2有點醜 properties spring.swagger2.version 2.6.1 spring.swagger2.version properties dependency groupid io.springfox groupid a...