java自動(dòng)生成接口文檔完整代碼示例
在平時(shí)的開發(fā)過程中必定要寫接口文檔 作為程序員 最煩的2件事
1、別人讓你寫接口文檔
2、接手別人的項(xiàng)目沒有接口文檔
由此可見 接口文檔確實(shí)是一件很繁瑣乏味卻又必不可少的工作,那么我們可否通過程序自動(dòng)生成接口文檔省去這一繁瑣的過程呢?
話不多說 上代碼!
maven依賴
要使用javamail的jar包首先需要導(dǎo)入依賴
<!--Swagger-UI API文檔生產(chǎn)工具--> <dependency> <groupId>io.springfox</groupId> <artifactId>springfox-swagger2</artifactId> <version>2.7.0</version> </dependency> <dependency> <groupId>io.springfox</groupId> <artifactId>springfox-swagger-ui</artifactId> <version>2.7.0</version> </dependency> <!--整合Knife4j--> <dependency> <groupId>com.github.xiaoymin</groupId> <artifactId>knife4j-spring-boot-starter</artifactId> <version>2.0.4</version> </dependency>
這里我們整合了swagger2和swagger-ui
swagger-ui是在swagger2的基礎(chǔ)上對頁面的展示效果進(jìn)行一定的優(yōu)化
工具類
Swagger2API文檔的配置
import com.github.xiaoymin.knife4j.spring.annotations.EnableKnife4j;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import springfox.documentation.builders.ApiInfoBuilder;
import springfox.documentation.builders.PathSelectors;
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;
/**
* Swagger2API文檔的配置
*/
@Configuration
@EnableSwagger2
@EnableKnife4j
public class Swagger2Config {
@Bean
public Docket createRestApi(){
return new Docket(DocumentationType.SWAGGER_2)
.apiInfo(apiInfo())
.select()
//為當(dāng)前包下controller生成API文檔
.apis(RequestHandlerSelectors.basePackage("huafu.controller"))
//為有@Api注解的Controller生成API文檔
// .apis(RequestHandlerSelectors.withClassAnnotation(Api.class))
//為有@ApiOperation注解的方法生成API文檔
// .apis(RequestHandlerSelectors.withMethodAnnotation(ApiOperation.class))
.paths(PathSelectors.any())
.build();
}
private ApiInfo apiInfo() {
return new ApiInfoBuilder()
.title("華富項(xiàng)目演示")
.description("huafu")
.version("1.0")
.build();
}
}
這個(gè)是接口返回的工具類
import io.swagger.annotations.ApiModelProperty;
/**
* 通用返回對象
* Created by macro on 2019/4/19.
*/
public class CommonResult<T> {
@ApiModelProperty(value = "返回代碼")
private String code;
@ApiModelProperty(value = "返回信息")
private String message;
@ApiModelProperty(value = "返回?cái)?shù)據(jù)")
private T data;
protected CommonResult() {
}
protected CommonResult(String code, String message, T data) {
this.code = code;
this.message = message;
this.data = data;
}
/**
* 成功返回結(jié)果
*
* @param data 獲取的數(shù)據(jù)
*/
public static <T> CommonResult<T> success(T data) {
return new CommonResult<T>(ResultCode.SUCCESS.getCode(), ResultCode.SUCCESS.getMessage(), data);
}
/**
* 成功返回結(jié)果
*
* @param data 獲取的數(shù)據(jù)
* @param message 提示信息
*
*/
public static <T> CommonResult<T> success(T data, String message) {
return new CommonResult<T>(ResultCode.SUCCESS.getCode(), message, data);
}
/**
* 失敗返回結(jié)果
* @param errorCode 錯(cuò)誤碼
*/
public static <T> CommonResult<T> failed(IErrorCode errorCode) {
return new CommonResult<T>(errorCode.getCode(), errorCode.getMessage(), null);
}
/**
* 失敗返回結(jié)果
* @param message 提示信息
*/
public static <T> CommonResult<T> failed(String message) {
return new CommonResult<T>(ResultCode.FAILED.getCode(), message, null);
}
/**
* 失敗返回結(jié)果
*/
public static <T> CommonResult<T> failed() {
return failed(ResultCode.FAILED);
}
/**
* 參數(shù)驗(yàn)證失敗返回結(jié)果
*/
public static <T> CommonResult<T> validateFailed() {
return failed(ResultCode.VALIDATE_FAILED);
}
/**
* 參數(shù)驗(yàn)證失敗返回結(jié)果
* @param message 提示信息
*/
public static <T> CommonResult<T> validateFailed(String message) {
return new CommonResult<T>(ResultCode.VALIDATE_FAILED.getCode(), message, null);
}
/**
* 未登錄返回結(jié)果
*/
public static <T> CommonResult<T> unauthorized(T data) {
return new CommonResult<T>(ResultCode.UNAUTHORIZED.getCode(), ResultCode.UNAUTHORIZED.getMessage(), data);
}
/**
* 未授權(quán)返回結(jié)果
*/
public static <T> CommonResult<T> forbidden(T data) {
return new CommonResult<T>(ResultCode.FORBIDDEN.getCode(), ResultCode.FORBIDDEN.getMessage(), data);
}
public String getCode() {
return code;
}
public void setCode(String code) {
this.code = code;
}
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
public T getData() {
return data;
}
public void setData(T data) {
this.data = data;
}
}
這里可以根據(jù)自己的實(shí)際需求自定義返回內(nèi)容
/**
* 枚舉了一些常用API操作碼
* Created by macro on 2019/4/19.
*/
public enum ResultCode implements IErrorCode {
SUCCESS("0", "成功"),
FAILED("500", "失??!"),
VALIDATE_FAILED("404", "參數(shù)檢驗(yàn)失敗"),
UNAUTHORIZED("401", "暫未登錄或token已經(jīng)過期"),
FORBIDDEN("403", "沒有相關(guān)權(quán)限");
private String code;
private String message;
private ResultCode(String code, String message) {
this.code = code;
this.message = message;
}
public String getCode() {
return code;
}
public String getMessage() {
return message;
}
}
/**
* 封裝API的錯(cuò)誤碼
* Created by macro on 2019/4/19.
*/
public interface IErrorCode {
String getCode();
String getMessage();
}
實(shí)體類 每個(gè)字段上面需要添加@ApiModelProperty對字段進(jìn)行結(jié)束說明
import io.swagger.annotations.ApiModelProperty;
import java.io.Serializable;
public class User implements Serializable {
@ApiModelProperty(value = "主鍵")
private Integer id;
@ApiModelProperty(value = "用戶名 郵箱地址")
private String userName;
@ApiModelProperty(value = "登陸密碼 md5加密")
private String password;
@ApiModelProperty(value = "郵箱地址")
private String email;
@ApiModelProperty(value = "matrixId")
private Integer matrixId;
@ApiModelProperty(value = "是否從matrix跳轉(zhuǎn) 1:是 0:否")
private Integer isMatrix;
@ApiModelProperty(value = "用戶狀態(tài) 1:正常 0:注銷")
private Integer status;
private static final long serialVersionUID = 1L;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName == null ? null : userName.trim();
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password == null ? null : password.trim();
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email == null ? null : email.trim();
}
public Integer getMatrixId() {
return matrixId;
}
public void setMatrixId(Integer matrixId) {
this.matrixId = matrixId;
}
public Integer getIsMatrix() {
return isMatrix;
}
public void setIsMatrix(Integer isMatrix) {
this.isMatrix = isMatrix;
}
public Integer getStatus() {
return status;
}
public void setStatus(Integer status) {
this.status = status;
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append(getClass().getSimpleName());
sb.append(" [");
sb.append("Hash = ").append(hashCode());
sb.append(", id=").append(id);
sb.append(", userName=").append(userName);
sb.append(", password=").append(password);
sb.append(", email=").append(email);
sb.append(", matrixId=").append(matrixId);
sb.append(", isMatrix=").append(isMatrix);
sb.append(", status=").append(status);
sb.append(", serialVersionUID=").append(serialVersionUID);
sb.append("]");
return sb.toString();
}
}
接下來的controller的配置
//接口文檔地址:http://localhost:8090/swagger-ui.html http://127.0.0.1:8090/doc.html
//自動(dòng)生成 執(zhí)行Generator中的main方法
@Api(tags = "TestController", description = "商品品牌管理")
@Controller
@RequestMapping("/test")
public class TestController {
private static Logger logger = LoggerFactory.getLogger(TestController.class);
@ApiImplicitParams({
@ApiImplicitParam(name = "id", value = "用戶ID", required=false, dataType = "Integer", paramType = "query")
})
@ApiOperation("測試普通請求方式")
@RequestMapping(value = "listAll", method = RequestMethod.GET)
@ResponseBody
public CommonResult<User> get(@RequestParam(value = "id", required = false) Integer id) {
User user = new User();
user.setId(1);
user.setEmail("xxxxxxx@qq.com");
user.setMatrixId(2);
user.setPassword("password");
user.setStatus(1);
user.setUserName("xxxx");
return CommonResult.success(user);
}
@ApiImplicitParams({
@ApiImplicitParam(name = "user", value = "用戶ID", required=false, dataType = "User", paramType = "body")
})
@ApiOperation("測試json請求方式")
@RequestMapping(value = "madan", method = RequestMethod.POST)
@ResponseBody
public CommonResult<User> post(@RequestBody User user, HttpServletRequest request, HttpServletResponse response) {
logger.info(" 獲取到的參數(shù) param:{}", user);
return CommonResult.success(user);
}
}
以上代碼即完成了所有自動(dòng)接口文檔的開發(fā) 接下來我們看看效果
展示效果
自動(dòng)接口文檔的訪問網(wǎng)址有2個(gè) 一個(gè)是默認(rèn)頁面 一個(gè)是UI優(yōu)化后的頁面
我這里項(xiàng)目的啟動(dòng)端口為8090 可以根據(jù)自己項(xiàng)目的端口修改訪問地址
默認(rèn)頁面:http://localhost:8090/swagger-ui.html
UI優(yōu)化后頁面:http://127.0.0.1:8090/doc.html
首頁

該頁面為默認(rèn)頁 頁面中紅框圈住1、2、3部分為Swagger2Config中設(shè)置
頁面中紅框圈住4部分為Controller中設(shè)置


接口頁
接口文檔頁面展示 具體的展示內(nèi)容為上面Controller中配置

自動(dòng)生成的接口文檔附帶自動(dòng)調(diào)用功能調(diào)試頁面

總結(jié)
到此這篇關(guān)于java自動(dòng)生成接口文檔的文章就介紹到這了,更多相關(guān)java自動(dòng)生成接口文檔內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
Java人民幣小寫轉(zhuǎn)大寫字符串的實(shí)現(xiàn)
這篇文章主要介紹了Java人民幣小寫轉(zhuǎn)大寫字符串的實(shí)現(xiàn),文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2021-04-04
java實(shí)現(xiàn)實(shí)時(shí)通信聊天程序
這篇文章主要為大家詳細(xì)介紹了java實(shí)現(xiàn)實(shí)時(shí)通信聊天程序,文中示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2022-06-06
Mybatis查不到數(shù)據(jù)查詢返回Null問題
mybatis突然查不到數(shù)據(jù),查詢返回的都是Null,但是 select count(*) from xxx查詢數(shù)量,返回卻是正常的。好多朋友遇到這樣的問題不知所措,下面小編通過本教程簡單給大家說明下2016-08-08
Spring的連接數(shù)據(jù)庫以及JDBC模板(實(shí)例講解)
下面小編就為大家?guī)硪黄猄pring的連接數(shù)據(jù)庫以及JDBC模板(實(shí)例講解)。小編覺得挺不錯(cuò)的,現(xiàn)在就分享給大家,也給大家做個(gè)參考。一起跟隨小編過來看看吧2017-10-10
SpringBoot @value注解動(dòng)態(tài)刷新問題小結(jié)
@Value注解 所對應(yīng)的數(shù)據(jù)源來自項(xiàng)目的 Environment 中,我們可以將數(shù)據(jù)庫或其他文件中的數(shù)據(jù),加載到項(xiàng)目的 Environment 中,然后 @Value注解 就可以動(dòng)態(tài)獲取到配置信息了,這篇文章主要介紹了SpringBoot @value注解動(dòng)態(tài)刷新,需要的朋友可以參考下2023-09-09
Java解析http協(xié)議字符串的方法實(shí)現(xiàn)
本文主要介紹了Java解析http協(xié)議字符串的方法實(shí)現(xiàn),我們探討了如何使用Java解析HTTP協(xié)議字符串,并將其封裝成了一個(gè)HttpRequest類,具有一定的參考價(jià)值,感興趣的可以了解一下2023-09-09

