前言:目前互联网开发市场都流行前后台真正的分离,后台提供数据API接口,前台负责请求数据并渲染。那么我们程序猿们在编写接口的时候,最不方便之处就是写完接口后需要进行文档的编写以及接口的测试。今天就介绍一款将接口文档编写和测试合并一起的集大成者Swagger,也是目前很多企业再用的一个API管理工具。此DEMO的开发环境是:MAVEN + Spring Boot 2.1.0 + JDK8 + Swagger2.9.2
1、快速构建Spring Boot项目
在https://start.spring.io/中选择Maven构建Java项目,然后选用Spring Boot2.1.0版本,Group是com.mage,Artifact是swagger_restful,Dependencies选择web,这样就能快速构建一个基于Spring Boot的web项目了。如下图:
项目构建
2、使用IDEA打开项目
解压swagger_restful.zip,然后使用idea导入项目,并执行SwaggerRestfulApplication.java,不报错说明项目构建成功
启动项目
3、pom导入swagger2的依赖jar包
<!-- 用于JSON API文档的生成-->
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger2</artifactId>
<version>2.9.2</version>
</dependency>
<!--用于文档界面展示-->
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger-ui</artifactId>
<version>2.9.2</version>
</dependency>
其中springfox-swagger2这个jar包是用于JSON API文档的生成,springfox-swagger-ui用于API文档界面生成,其他版本请参考:https://mvnrepository.com/artifact/io.springfox/springfox-swagger2和https://mvnrepository.com/artifact/io.springfox/springfox-swagger-ui
5、编写测试的Controller和Model(TestController和Test)
编写一个Test的数据模型
package com.mage.swagger_restful.model;
public class Test {
private Integer id;
private String content;
private Integer isValid;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getContent() {
return content;
}
public void setContent(String content) {
this.content = content;
}
public Integer getIsValid() {
return isValid;
}
public void setIsValid(Integer isValid) {
this.isValid = isValid;
}
}
基于Restful规则,编写