目錄
一、簡介以及使用
二、整合步驟
三、註解說明
一、簡介以及使用
號稱:世界最流行的API框架
解決什麼問題:
在前後臺分離的開發模式中,減小接口定義溝通成本,方便開發過程中測試,自動生成接口文檔
使用方式:
1、通過官網配置文檔,一個接口一個接口編寫
2、通多註解配置,動態生成json數據,由框架自動生成代碼展示
二、整合步驟
項目框架要求:本文以springboot
1、在pom文件中引入swagger支持的相關依賴---即jar包
<!--依賴管理 -->
<dependencies>
<dependency> <!--添加Web依賴 -->
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency><!--添加Swagger依賴 -->
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger2</artifactId>
<version>2.7.0</version>
</dependency>
<dependency><!--添加Swagger-UI依賴 -->
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger-ui</artifactId>
<version>2.7.0</version>
</dependency>
<dependency> <!--添加熱部署依賴 -->
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-devtools</artifactId>
</dependency>
<dependency><!--添加Test依賴 -->
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
2、添加配置---即編寫swagger啓動類SwaggerConfig.java
package dcc.core;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import springfox.documentation.builders.ApiInfoBuilder;
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 //聲明啓動Swagger2
public class SwaggerConfig{
@Bean
public Docket customDocket() {
return new Docket(DocumentationType.SWAGGER_2)
.apiInfo(apiInfo())
.select()
.apis(RequestHandlerSelectors.basePackage("com.epoch.ccfindcars.controller"))//掃描的包路徑
.build();
}
private ApiInfo apiInfo() {
return new ApiInfoBuilder()
.title("反向尋車")//文檔說明
.version("1.0.0")//文檔版本說明
.build();
}
}
3、編寫接口文檔----即開啓spring整合swagger配置
Swagger2 基本使用:
- @Api 描述類/接口的主要用途
- @ApiOperation 描述方法用途
- @ApiImplicitParam 描述方法的參數
- @ApiImplicitParams 描述方法的參數(Multi-Params)
- @ApiIgnore 忽略某類/方法/參數的文檔
Swagger2 使用註解來編寫文檔:
Swagger2編寫接口文檔相當簡單,只需要在控制層(Controller)添加註解來描述接口信息即可。
package com.epoch.ccfindcars.controller;
import com.epoch.ccfindcars.entity.LotAddress;
import com.epoch.ccfindcars.entity.LotAddressList;
import com.epoch.ccfindcars.service.LotAddressService;
import com.epoch.ccfindcars.service.LotAddressServiceList;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import java.util.List;
/**
* @Author: ljj
* @Description: 反向尋車功能
* @Date:
*/
@RestController
@Api("反向尋車管理功能")
public class ReverseForCarController {
@Autowired
private LotAddressService lotAddressService;
@Autowired
private LotAddressServiceList lotAddressServiceList;
@ApiOperation("通過id確定唯一車牌")
@GetMapping("/getone")
@ApiImplicitParam(name = "id",value = "車位表對應的id",dataType = "int ")
public LotAddress getOneCatLotAddress(int id) {
LotAddress lotAddress = lotAddressService.OneCatLotAddress(id);
return lotAddress;
}
/**
* 快速尋車:通過輸入車牌中的一個或多個字母或數字,快速查詢車位
*
* @param carLicense
* @return lotAddressList
*/
@ApiOperation("通過車牌號,獲取相關車牌列表")
@GetMapping("/serchlike")
@ApiImplicitParam(name = "carLicense",value = "車牌號",dataType = "String")
public List<LotAddressList> getCarLotAddress(String[] carLicense) {
StringBuffer sc = new StringBuffer();
for (int i = 0; i < carLicense.length; i++) {
sc.append(carLicense[i]);
}
String s = sc.toString();
System.out.println(s);
List<LotAddressList> lotAddressList = lotAddressServiceList.getCatAllRow(s);
return lotAddressList;
}
@ApiOperation("通過車位號來獲取車位")
@GetMapping("/findcar")
@ApiImplicitParam(name = "carAddress",value = "車位號",dataType = "String")
public List<LotAddressList> getCarAddressByCarAddress(String carAddress) {
List<LotAddressList> carAddressByCarLicense = lotAddressService.findCarAddressByCarLicense(carAddress);
return carAddressByCarLicense;
}
}
4查閱接口文檔
編寫文檔完成之後,啓動當前項目,在瀏覽器打開:
[ http://localhost:4040/swagger-ui.html ] --(端口根據自己設置來寫)看到效果如下:
5測試接口
Swagger2的強大之處不僅在於快速生成整潔優雅的RestAPI文檔,同時支持接口方法的測試操作(類似於客戶端PostMan)。
以通過車位號獲取車位爲例,隨便輸入參數5,直接點擊“試一下”按鈕:
6.此外,本教程還額外提供了UI漢化教程,去除閱讀官方英文界面的煩惱。(目前Swagger漢化教程是找不到的,因爲官方手冊實在寫得太爛。。)
①.默認的英文界面UI
想必很多小夥伴都曾經使用過Swagger,但是打開UI界面之後,卻是下面這樣的畫風,純英文的界面並不太友好,作爲國人還是習慣中文界面。
②.定製中文界面
2.1添加首頁和譯文
重點來了,在src/main/resources
目錄下創建META-INF\resources
目錄,然後創建一個名稱爲"swagger-ui.html" 的HTML文件。如圖:
注意文件名不要起錯,接下來將下面這段內容原封不動的拷貝進去。
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Swagger UI</title>
<link rel="icon" type="image/png" href="webjars/springfox-swagger-ui/images/favicon-32x32.png" sizes="32x32"/>
<link rel="icon" type="image/png" href="webjars/springfox-swagger-ui/images/favicon-16x16.png" sizes="16x16"/>
<link href='webjars/springfox-swagger-ui/css/typography.css' media='screen' rel='stylesheet' type='text/css'/>
<link href='webjars/springfox-swagger-ui/css/reset.css' media='screen' rel='stylesheet' type='text/css'/>
<link href='webjars/springfox-swagger-ui/css/screen.css' media='screen' rel='stylesheet' type='text/css'/>
<link href='webjars/springfox-swagger-ui/css/reset.css' media='print' rel='stylesheet' type='text/css'/>
<link href='webjars/springfox-swagger-ui/css/print.css' media='print' rel='stylesheet' type='text/css'/>
<script src='webjars/springfox-swagger-ui/lib/object-assign-pollyfill.js' type='text/javascript'></script>
<script src='webjars/springfox-swagger-ui/lib/jquery-1.8.0.min.js' type='text/javascript'></script>
<script src='webjars/springfox-swagger-ui/lib/jquery.slideto.min.js' type='text/javascript'></script>
<script src='webjars/springfox-swagger-ui/lib/jquery.wiggle.min.js' type='text/javascript'></script>
<script src='webjars/springfox-swagger-ui/lib/jquery.ba-bbq.min.js' type='text/javascript'></script>
<script src='webjars/springfox-swagger-ui/lib/handlebars-4.0.5.js' type='text/javascript'></script>
<script src='webjars/springfox-swagger-ui/lib/lodash.min.js' type='text/javascript'></script>
<script src='webjars/springfox-swagger-ui/lib/backbone-min.js' type='text/javascript'></script>
<script src='webjars/springfox-swagger-ui/swagger-ui.min.js' type='text/javascript'></script>
<script src='webjars/springfox-swagger-ui/lib/highlight.9.1.0.pack.js' type='text/javascript'></script>
<script src='webjars/springfox-swagger-ui/lib/highlight.9.1.0.pack_extended.js' type='text/javascript'></script>
<script src='webjars/springfox-swagger-ui/lib/jsoneditor.min.js' type='text/javascript'></script>
<script src='webjars/springfox-swagger-ui/lib/marked.js' type='text/javascript'></script>
<script src='webjars/springfox-swagger-ui/lib/swagger-oauth.js' type='text/javascript'></script>
<script src='webjars/springfox-swagger-ui/springfox.js' type='text/javascript'></script>
<!--國際化操作:選擇中文版 -->
<script src='webjars/springfox-swagger-ui/lang/translator.js' type='text/javascript'></script>
<script src='webjars/springfox-swagger-ui/lang/zh-cn.js' type='text/javascript'></script>
</head>
<body class="swagger-section">
<div id='header'>
<div class="swagger-ui-wrap">
<a id="logo" href="http://swagger.io">![](webjars/springfox-swagger-ui/images/logo_small.png)<span class="logo__title">swagger</span></a>
<form id='api_selector'>
<div class='input'>
<select id="select_baseUrl" name="select_baseUrl"></select>
</div>
<div class='input'><input placeholder="http://example.com/api" id="input_baseUrl" name="baseUrl" type="text"/></div>
<div id='auth_container'></div>
<div class='input'><a id="explore" class="header__btn" href="#" data-sw-translate>Explore</a></div>
</form>
</div>
</div>
<div id="message-bar" class="swagger-ui-wrap" data-sw-translate> </div>
<div id="swagger-ui-container" class="swagger-ui-wrap"></div>
</body>
</html>
OK 大功告成 我們訪問 http://localhost:4040/swagger-ui.html 看看顯示效果:
2.2更詳細的譯文翻譯(非必需)
如果想進一步調整譯文,可以在META-INF\resources\webjars\springfox-swagger-ui\lang 目錄下添加zh-cn.js文件.
然後在譯文(zh-cn.js )根據個人喜好來添加翻譯內容,如下
'use strict';
/* jshint quotmark: double */
window.SwaggerTranslator.learn({
"Warning: Deprecated":"警告:已過時",
"Implementation Notes":"實現備註",
"Response Class":"響應類",
"Status":"狀態",
"Parameters":"參數",
"Parameter":"參數",
"Value":"值",
"Description":"描述",
"Parameter Type":"參數類型",
"Data Type":"數據類型",
"Response Messages":"響應消息",
"HTTP Status Code":"HTTP狀態碼",
"Reason":"原因",
"Response Model":"響應模型",
"Request URL":"請求URL",
"Response Body":"響應體",
"Response Code":"響應碼",
"Response Headers":"響應頭",
"Hide Response":"隱藏響應",
"Headers":"頭",
"Try it out!":"試一下!",
"Show/Hide":"顯示/隱藏",
"List Operations":"顯示操作",
"Expand Operations":"展開操作",
"Raw":"原始",
"can't parse JSON. Raw result":"無法解析JSON. 原始結果",
"Example Value":"示例",
"Click to set as parameter value":"點擊設置參數",
"Model Schema":"模型架構",
"Model":"模型",
"apply":"應用",
"Username":"用戶名",
"Password":"密碼",
"Terms of service":"服務條款",
"Created by":"創建者",
"See more at":"查看更多:",
"Contact the developer":"聯繫開發者",
"api version":"api版本",
"Response Content Type":"響應Content Type",
"Parameter content type:":"參數類型:",
"fetching resource":"正在獲取資源",
"fetching resource list":"正在獲取資源列表",
"Explore":"瀏覽",
"Show Swagger Petstore Example Apis":"顯示 Swagger Petstore 示例 Apis",
"Can't read from server. It may not have the appropriate access-control-origin settings.":"無法從服務器讀取。可能沒有正確設置access-control-origin。",
"Please specify the protocol for":"請指定協議:",
"Can't read swagger JSON from":"無法讀取swagger JSON於",
"Finished Loading Resource Information. Rendering Swagger UI":"已加載資源信息。正在渲染Swagger UI",
"Unable to read api":"無法讀取api",
"from path":"從路徑",
"server returned":"服務器返回"
});
三、常用註解說明
1、常用註解
@Api()用於類;
表示標識這個類是swagger的資源
@ApiOperation()用於方法;
表示一個http請求的操作
@ApiParam()用於方法,參數,字段說明;
表示對參數的添加元數據(說明或是否必填等)
@ApiModel()用於類
表示對類進行說明,用於參數用實體類接收
@ApiModelProperty()用於方法,字段
表示對model屬性的說明或者數據操作更改
@ApiIgnore()用於類,方法,方法參數
表示這個方法或者類被忽略
@ApiImplicitParam() 用於方法
表示單獨的請求參數
@ApiImplicitParams() 用於方法,包含多個 @ApiImplicitParam
@ApiResponse
返回參數
2、具體使用
@Api()用於類;
參數:
tags:表示說明,tags如果有多個值,會生成多個list
value:已廢用
hidde:無效果
description:接口說明
代碼:
界面效果:
@ApiOperation()用於方法;
value用於方法描述
notes用於提示內容
tags可以重新分組(視情況而用)
代碼:
文檔效果:
@ApiImplicitParam() 用於方法
表示單獨的請求參數
@ApiImplicitParams() 用於方法,包含多個 @ApiImplicitParam
name–參數名
value–參數說明
dataType–數據類型
paramType–參數類型
@ApiResponse
返回參數說明
response:返回的對象信息
code:返回的狀態信息
message:返回的文本信息
對象信息具體註釋
@ApiModelProperty
對象字段說明
value:字段名稱
example: 字段說明