背景介紹
在進(jìn)行前后端分離式開發(fā)項(xiàng)目過程中镐牺,需要有效的溝通。接口文檔因?yàn)楦碌牟患皶r(shí)焦读,也難免存在錯(cuò)誤子库,使溝通的成本大大增加。因此矗晃,業(yè)界就出現(xiàn)了一些根據(jù)代碼自動(dòng)生成 Restful API 文檔的開源項(xiàng)目仑嗅,與 Spring Boot 結(jié)合比較好的是 Swagger2,Swagger2 通過讀取 Controller代碼中的注解信息张症,來自動(dòng)生成 API 文檔仓技,可以節(jié)省大量的手工編寫文檔的工作量。我之前也是用的 Swagger2俗他,但發(fā)現(xiàn) Swagger2 也有好多地方用得不爽脖捻,如注解非常臃腫、頁面排版不太友好兆衅。想學(xué)習(xí)使用Swagger2的請參考Spring-Boot-項(xiàng)目中使用Swagger2地沮。Api2Doc 專注于 Restful API 文檔的自動(dòng)生成,它的原理與 Swagger2 是類似的羡亩,都是通過反射诉濒,分析 Controller 中的信息生成文檔,但它要比 Swagger2 好很多夕春,最大的不同是Api2Doc 比 Swagger2 要少寫很多代碼未荒。
使用Api2Doc
創(chuàng)建SpringBoot工程
具體創(chuàng)建步驟略,可參考使用STS創(chuàng)建Spring-Boot-項(xiàng)目及志。
在工程中引入Maven依賴
<dependency>
<groupId>com.github.terran4j</groupId>
<artifactId>terran4j-commons-api2doc</artifactId>
<version>1.0.2</version>
</dependency>
啟用 Api2Doc 服務(wù)
在有 @SpringBootApplication 注解的類上片排,添加 @EnableApi2Doc
注解,以啟用 Api2Doc 服務(wù)速侈。
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import com.terran4j.commons.api2doc.config.EnableApi2Doc;
@EnableApi2Doc
@SpringBootApplication
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}
具體示例
給 Controller 類上添加文檔注解
package cn.com.yd.exam.controller;
import java.util.List;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import com.terran4j.commons.api2doc.annotations.Api2Doc;
import com.terran4j.commons.api2doc.annotations.ApiComment;
import com.terran4j.commons.api2doc.annotations.ApiError;
import cn.com.yd.exam.bean.User;
import cn.com.yd.exam.bean.UserType;
@Api2Doc(id = "demo1", name = "用戶接口", order = 1)
@ApiComment(seeClass = User.class)
@RestController
@RequestMapping(value = "/apis/v1/demo/users")
public class UserController {
@Api2Doc(order = 1)
@ApiComment("添加一個(gè)新的用戶率寡。")
@ApiError(value = "user.exists", comment = "此用戶已經(jīng)存在!")
@PostMapping(name = "新增用戶",value="")
public User addUser(
@ApiComment("用戶所在部門名稱") @RequestParam(required = true) String dept,
@ApiComment("用戶名稱") @RequestParam(required = true) String name,
@ApiComment("用戶密碼") @RequestParam(required = true) String password,
@ApiComment("用戶類型") @RequestParam(required = true) UserType type) {
User user = new User();
user.setDept(dept).setName(name).setPassword(password).setType(type);
return user; // TODO: 還未實(shí)現(xiàn)倚搬。
}
@Api2Doc(order = 2)
@ApiComment("根據(jù)用戶id冶共,刪除指定的用戶")
@ApiError(value = "user.not.found", comment = "此用戶不存在!")
@ApiError(value = "admin.cant.delete", comment = "不允許刪除管理員用戶每界!")
@DeleteMapping(name = "刪除指定用戶", value = "/{id}")
public void delete(@PathVariable("id") Long id) {
}
@Api2Doc(order = 3)
@ApiComment("根據(jù)用戶id捅僵,查詢此用戶的信息")
@ApiError(value = "user.not.found", comment = "此用戶不存在!")
@GetMapping(name = "查詢單個(gè)用戶", value = "{id}")
public User getUser(@PathVariable("id") Long id) {
return null; // TODO: 還未實(shí)現(xiàn)眨层。
}
@Api2Doc(order = 4)
@ApiComment("查詢所有用戶庙楚,按注冊時(shí)間進(jìn)行排序。")
@GetMapping(name = "查詢用戶列表",value="")
public List<User> getUsers() {
return null; // TODO: 還未實(shí)現(xiàn)趴樱。
}
}
User類定義
package cn.com.yd.exam.bean;
import java.util.Date;
import com.terran4j.commons.api2doc.annotations.ApiComment;
import com.terran4j.commons.restpack.RestPackIgnore;
import lombok.Data;
import lombok.experimental.Accessors;
@Data
@Accessors(chain = true)
public class User {
@ApiComment(value = "用戶id", sample = "123")
private Long id;
@ApiComment(value = "用戶名", sample = "terran4j")
private String name;
@ApiComment(value = "賬號(hào)密碼,字母與數(shù)字的組合,區(qū)分大小寫馒闷,8-12位", sample = "sdfi23skvs")
private String password;
@ApiComment(value = "用戶所在的部門", sample = "研發(fā)組")
private String dept;
@ApiComment(value = "用戶類型", sample = "admin")
private UserType type;
@ApiComment(value = "是否已刪除", sample = "true")
@RestPackIgnore
private Boolean deleted;
@ApiComment(value = "創(chuàng)建時(shí)間,也是注冊時(shí)間酪捡。",sample="2018-12-12")
private Date createTime;
}
UserType枚舉定義
package cn.com.yd.exam.bean;
import com.terran4j.commons.api2doc.annotations.ApiComment;
public enum UserType {
@ApiComment("管理員")
admin,
@ApiComment("普通用戶")
user
}
運(yùn)行效果
在瀏覽器中輸入http://localhost:8080/api2doc/home.html,即可訪問ApiDoc接口文檔纳账,如下圖
一些細(xì)節(jié)的設(shè)置
設(shè)置接口文檔的標(biāo)題
可在application.properties中進(jìn)行接口文檔的標(biāo)題和圖標(biāo)的設(shè)置逛薇,圖標(biāo)為一個(gè)全路徑 URL,或本站點(diǎn)相對路徑 URL 都行疏虫。
# 中文標(biāo)題出現(xiàn)亂碼的問題金刁,故此設(shè)置成英文的了
api2doc.title=Financial Information System APIs Document
# 圖標(biāo)為一個(gè)全路徑 URL,或本站點(diǎn)相對路徑 URL 都行
api2doc.icon=https://spring.io/img/homepage/icon-spring-framework.svg
開啟和關(guān)閉 Api2Doc 服務(wù)
由于Api2Doc服務(wù)沒有訪問權(quán)限校驗(yàn)议薪,建議僅在受信任的網(wǎng)絡(luò)環(huán)境如公司內(nèi)網(wǎng)中才啟用 Api2Doc 服務(wù)尤蛮。可在application.properties中配置api2doc.enabled屬性斯议,以開啟或關(guān)閉 Api2Doc 服務(wù)产捞,api2doc.enabled=true或者不寫表示啟用。
api2doc.enabled=false
定制歡迎頁面
每次訪問文檔頁面http://localhost:8080/api2doc/home.html 時(shí)哼御,
中間的內(nèi)容是非常簡單的一句:
歡迎使用 Api2Doc 坯临!
這似乎有點(diǎn)不太好,我們可以編寫自己的歡迎頁恋昼。
方法很簡單看靠,在 src/main/resources 目錄下創(chuàng)建api2doc 目錄,然后在api2doc目錄下創(chuàng)建一個(gè)名為
welcome.md 的文件(這個(gè)名稱是固定的)液肌,然后用 md 語法編寫內(nèi)容就可以挟炬。
給文檔菜單項(xiàng)排序
可以用@Api2Doc中的order屬性給菜單項(xiàng)排序,order的值越小該菜單項(xiàng)就越排在前面嗦哆。@Api2Doc既可以用在類上又可以用在方法上谤祖。
@Api2Doc(order = 4)
Api2Doc注解詳解
@Api2Doc
@Api2Doc 用于對文檔的生成進(jìn)行控制。
@Api2Doc 修飾在類上老速,表示這個(gè)類會(huì)參與到文檔生成過程中粥喜,Api2Doc 服務(wù)會(huì)掃描 Spring 容器中所有的 Controller 類,只有類上有 @Api2Doc 的類橘券,才會(huì)被生成文檔额湘,一個(gè)類對應(yīng)于文檔頁面左側(cè)的一級(jí)菜單項(xiàng),@Api2Doc的name 屬性則表示這個(gè)菜單項(xiàng)的名稱旁舰。
@Api2Doc 也可以修飾在方法锋华,不過在方法上的 @Api2Doc 通常是可以省略,Api2Doc服務(wù)會(huì)掃描這個(gè)類的所有帶有@RequestMapping的方法鬓梅,每個(gè)這樣的方法對應(yīng)文檔頁面的左側(cè)的二級(jí)菜單項(xiàng)供置,菜單項(xiàng)的名稱取@RequestMapping的name屬性谨湘,當(dāng)然您仍然可以在方法上用 @Api2Doc的name屬性進(jìn)行重定義绽快。
@ApiComment
@ApiComment用于對API進(jìn)行說明芥丧,它可以修飾在很多地方:
修飾在類上,表示對這組API接口進(jìn)行說明坊罢;
修飾在方法上续担,表示對這個(gè)API接口進(jìn)行說明;
修飾在參數(shù)上活孩,表示對這個(gè)API接口的請求參數(shù)進(jìn)行說明物遇;
修飾在返回類型的屬性上,表示對這個(gè)API接口的返回字段進(jìn)行說明憾儒;
修飾在枚舉項(xiàng)上询兴,表示對枚舉項(xiàng)進(jìn)行說明;
如果相同名稱起趾、相同意義的屬性或參數(shù)字段诗舰,其說明已經(jīng)在別的地方定義過了,
可以用 @ApiComment的seeClass屬性表示采用指定類的同名字段上的說明信息训裆。
@ApiError
@ApiError用于定義錯(cuò)誤碼眶根,有的API方法在執(zhí)行業(yè)務(wù)邏輯時(shí)會(huì)產(chǎn)生錯(cuò)誤,出錯(cuò)后會(huì)在返回報(bào)文包含錯(cuò)誤碼边琉,以方便客戶端根據(jù)錯(cuò)誤碼作進(jìn)一步的處理属百,因此也需要在API文檔上體現(xiàn)錯(cuò)誤碼的說明。
Api2Doc的缺點(diǎn)
Api2Doc的缺點(diǎn)是不能像Swagger那樣在頁面中進(jìn)行測試变姨,不過可以借助其他的工具進(jìn)行測試族扰。