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ǔ)上對(duì)頁面的展示效果進(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;
/**
* 通用返回對(duì)象
* 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對(duì)字段進(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("測試普通請(qǐng)求方式")
@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請(qǐng)求方式")
@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)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
spring boot使用thymeleaf為模板的基本步驟介紹
Spring Boot項(xiàng)目的默認(rèn)模板引擎是Thymeleaf,這沒什么好說的,個(gè)人覺得也非常好,下面這篇文章主要給大家介紹了關(guān)于spring boot使用thymeleaf為模板的相關(guān)資料,需要的朋友可以參考借鑒,下面來一起學(xué)習(xí)學(xué)習(xí)吧。2018-01-01
JavaIO?BufferedReader和BufferedWriter使用及說明
這篇文章主要介紹了JavaIO?BufferedReader和BufferedWriter使用及說明,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2022-12-12
JAVA CountDownLatch與thread-join()的區(qū)別解析
這篇文章主要介紹了JAVA CountDownLatch與thread-join()的區(qū)別解析,文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下2019-08-08
Java實(shí)現(xiàn)Flappy Bird游戲源碼
這篇文章主要為大家詳細(xì)介紹了Java實(shí)現(xiàn)Flappy Bird游戲源碼,具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2018-12-12
Java實(shí)現(xiàn)基礎(chǔ)銀行ATM系統(tǒng)
這篇文章主要為大家詳細(xì)介紹了Java實(shí)現(xiàn)基礎(chǔ)銀行ATM系統(tǒng),文中示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2022-05-05

