使用springfox+swagger2書寫API文檔(十八)
使用springfox+swagger2書寫API文檔
springfox是通過註解的形式自動生成API文檔,利用它,可以很方便的書寫restful
API,swagger主要用於展示springfox生成的API文檔,筆者將主要介紹springfox的配置與使用,文中spring版本為4.2.6.RELEASE,springfox版本為2.6.1,使用Maven進行項目依賴管理。
Maven依賴配置
下面是Maven pom.xml配置信息
<properties>
<springfoxversion>2.6.1</springfoxversion>
</properties>
<dependencies>
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger2</artifactId>
<version>${springfoxversion}</version>
<scope>compile</scope>
</dependency>
</dependencies>
如果啟動項目時出現com/fasterxml/jackson/databind/ObjectMapper
類找不到,請加入下面依賴
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.6.6</version>
</dependency>
Configuration類配置
下面是基礎配置類,下面類中的.apiInfo()
/*
省略 package name
*/
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import springfox.documentation.service.ApiInfo;
import springfox.documentation.service.Contact;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2;
@Configuration //必須存在
@EnableSwagger2 //必須存在
@EnableWebMvc //必須存在
@ComponentScan(basePackages = {"org.blog.controller"}) //必須存在 掃描的API Controller package name 也可以直接掃描class (basePackageClasses)
public class WebAppConfig{
@Bean
public Docket customDocket() {
//
return new Docket(DocumentationType.SWAGGER_2)
.apiInfo(apiInfo());
}
private ApiInfo apiInfo() {
Contact contact = new Contact("周發揚", "https://cc520.me", "[email protected]");
return new ApiInfo("Blog前臺API接口",//大標題 title
"Blog前臺API接口",//小標題
"0.0.1",//版本
"www.fangshuoit.com",//termsOfServiceUrl
contact,//作者
"Blog",//鏈接顯示文字
"https://cc520.me"//網站鏈接
);
}
}
註意:當前類一定要讓spring在加載時候能掃描到配置類。
springfox使用
添加了配置類,我們開始創建一個Controller類(一定要讓上一步配置類中的@ComponentScan掃描到),並在類中使用註解配置API信息。
下面類中沒有添加全局異常處理,如果傳遞的參數類型和接收類型不匹配等情況,會拋出異常信息,請自行添加全局異常處理。
/*
*省略package 和 部分 improt
*/
import io.swagger.annotations.*;
@Controller
@RequestMapping(value = "/v1/api")
public class HomeApiController{
//這裏使用POST @RequestBody必須使用POST才能接收,這裏方便講解
@ApiOperation(value = "一個測試API", notes = "第一個測試API")
@ResponseBody
@RequestMapping(value = "/test/{path}", method = RequestMethod.POST)
@ApiImplicitParams({
@ApiImplicitParam(name = "blogArticleBeen", value = "文檔對象", required = true, paramType = "body", dataType = "BlogArticleBeen"),
@ApiImplicitParam(name = "path", value = "url上的數據", required = true, paramType = "path", dataType = "Long"),
@ApiImplicitParam(name = "query", value = "query類型參數", required = true, paramType = "query", dataType = "String"),
@ApiImplicitParam(name = "apiKey", value = "header中的數據", required = true, paramType = "header", dataType = "String")
})
public JSONResult test(@RequestBody BlogArticleBeen blogArticleBeen,
@PathVariable Long path,
String query,
@RequestHeader String apiKey,
PageInfoBeen pageInfoBeen){
System.out.println("blogArticleBeen.getLastUpdateTime():"+blogArticleBeen.getLastUpdateTime());
System.out.println("blogArticleBeen.getSorter():"+blogArticleBeen.getSorter());
System.out.println("path:"+path);
System.out.println("query:"+query);
System.out.println("apiKey:"+apiKey);
System.out.println("pageInfoBeen.getNowPage():"+pageInfoBeen.getNowPage());
System.out.println("pageInfoBeen.getPageSize():"+pageInfoBeen.getPageSize());
JSONResult jsonResult = new JSONResult();
jsonResult.setMessage("success");
jsonResult.setMessageCode(null);
jsonResult.setCode(0);
jsonResult.setBody(null);
return jsonResult;
}
}
BlogArticleBeen.java
//省略 package import
public class BlogArticleBeen {
private Long id;
private String name; //標題
private String mainPhoto; //封面圖片
private String sketch; //簡述
private String content; //詳細描述
private String contentMd; //詳細描述 markdown
private Boolean ifTop; //是否置頂
private String sources; //來源
private String staticCode; //靜態碼
private BigDecimal sorter;
private Boolean status; //狀態
@ApiModelProperty(hidden = true)
private String creater;
@ApiModelProperty(dataType = "java.util.Date")
private Timestamp lastUpdateTime;
@ApiModelProperty(dataType = "java.util.Date")
private Timestamp creatTime;
private String columnNamesCache;
private String columnIdsCache;
private String labelIdsCache;
private String labelNamesCache;
//省略 set get
}
PageInfoBeen.java
//省略 package import
public class PageInfoBeen {
@ApiParam(value = "當前頁", required = true)
private Integer nowPage;
@ApiModelProperty(value = "每頁大小", required = true)
private Integer pageSize;
//省略 set get
}
JSONResult.java
//省略 package import
public class JSONResult {
private String message;
private int code = -1;
private String messageCode;
private Object body;
//省略 set get
}
完成以上操作,我們就已經可以實際看到springfox為我們生成的API json字符串了,重啟服務器,在瀏覽器中訪問http://127.0.0.1:port/v2/api-docs
(如果添加了group信息,請參考springfox官方文檔),出現下圖展示的信息說明配置正確。
如果沒有得到這個結果,檢查一下是否更換了MessageConverter為fastjson的,如果有,請升級fastjson為最新版本再測試。
####springfox、swagger.annotations.*註解部分參數介紹
在上面只展示了如何使用,這裏將對上面添加的swagger註解進行說明,筆記使用時參考了swagger annotations Api 手冊,接下來進行部分常用註解使用說明介紹。
- @ApiIgnore 忽略註解標註的類或者方法,不添加到API文檔中
-
@ApiOperation 展示每個API基本信息
- value api名稱
- notes 備註說明
-
@ApiImplicitParam 用於規定接收參數類型、名稱、是否必須等信息
- name 對應方法中接收參數名稱
- value 備註說明
- required 是否必須 boolean
- paramType 參數類型 body、path、query、header、form中的一種
- body 使用@RequestBody接收數據 POST有效
- path 在url中配置{}的參數
- query 普通查詢參數 例如 ?query=q ,jquery ajax中data設置的值也可以,例如 {query:”q”},springMVC中不需要添加註解接收
- header 使用@RequestHeader接收數據
- form 筆者未使用,請查看官方API文檔
- dataType 數據類型,如果類型名稱相同,請指定全路徑,例如 dataType = “java.util.Date”,springfox會自動根據類型生成模型
-
@ApiImplicitParams 包含多個@ApiImplicitParam
-
@ApiModelProperty 對模型中屬性添加說明,例如 上面的PageInfoBeen、BlogArticleBeen這兩個類中使用,只能使用在類中。
- value 參數名稱
- required 是否必須 boolean
- hidden 是否隱藏 boolean
其他信息和上面同名屬性作用相同,hidden屬性對於集合不能隱藏,目前不知道原因
-
@ApiParam 對單獨某個參數進行說明,使用在類中或者controller方法中都可以。註解中的屬性和上面列出的同名屬性作用相同
以上為主要常用的註解介紹,請結合springfox使用查看
使用swagger2展示API文檔
通過上述配置,我們已經完成了API數據生成,現在我們只需要使用swagger2 UI展示API文檔即可
訪問github:下載swagger-ui,下載zip文件,解壓後把裏面的dist目錄下的所有文件考入springMVC的靜態資源下,修改拷貝的index.html文件,替換下面的js代碼:
var baseUrl = "";
$(function () {
var url = window.location.search.match(/url=([^&]+)/);
if (url && url.length > 1) {
url = decodeURIComponent(url[1]);
} else {
//上面描述的api-docs地址
url = baseUrl + "/v2/api-docs";
}
// Pre load translate...
if (window.SwaggerTranslator) {
window.SwaggerTranslator.translate();
}
window.swaggerUi = new SwaggerUi({
url: url,
validatorUrl: undefined,
dom_id: "swagger-ui-container",
supportedSubmitMethods: [‘get‘, ‘post‘, ‘put‘, ‘delete‘, ‘patch‘],
onComplete: function (swaggerApi, swaggerUi) {
if (typeof initOAuth == "function") {
initOAuth({
clientId: "your-client-id",
clientSecret: "your-client-secret-if-required",
realm: "your-realms",
appName: "your-app-name",
scopeSeparator: ",",
additionalQueryStringParams: {}
});
}
if (window.SwaggerTranslator) {
window.SwaggerTranslator.translate();
}
$(‘pre code‘).each(function (i, e) {
hljs.highlightBlock(e)
});
addApiKeyAuthorization();
},
onFailure: function (data) {
log("Unable to Load SwaggerUI");
},
docExpansion: "none",
jsonEditor: false,
apisSorter: "alpha",
defaultModelRendering: ‘schema‘,
showRequestHeaders: false
});
//這裏可以添加權限認證,例如token
function addApiKeyAuthorization() {
var token = "you-token";
var tokenHeader = new SwaggerClient.ApiKeyAuthorization("token", token, "header");
window.swaggerUi.api.clientAuthorizations.add("token", tokenHeader);
}
window.swaggerUi.load();
function log() {
if (‘console‘ in window) {
console.log.apply(console, arguments);
}
}
});
完成了以上配置,直接訪問修改的index.html,出現下面頁面表示成功:
總結
通過以上步驟已經完成基本springfox+swagger-ui的基本配置,其他更新詳細使用方法請查看springfox官網和swagger官網,如文章中有錯誤信息,請聯系筆者進行更改。
使用springfox+swagger2書寫API文檔(十八)