现在我们大多都是做的前后端分离的项目,那后台开发人员就难免需要编写接口文档提供给前端开发人员进行接口调试。虽说市面上已经有很多文档工具,如 ShowDoc 。而编写接口文档本身也是件比较耗时的事情,为了节省在这方面的耗时,Swagger 也就应运而生了。
使用 Swagger2 可以自动生成 RestFul API 接口文档, 并且以页面的形式展示出来,还提供了接口调试功能。一看这些功能,就感觉很舒服了。
👀 这里提醒一下,Swagger 是一款基于 RESTFul 风格的 API 文档生成工具,所以我们需要提前对 RESTFul 有一个了解,如何编写 RESTFul 风格的接口是至关重要的。
1. 添加依赖
<swagger.version>2.9.2</swagger.version>
<!-- swagger2 -->
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger2</artifactId>
<version>${swagger.version}</version>
</dependency>
<!-- swagger-ui -->
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger-ui</artifactId>
<version>${swagger.version}</version>
</dependency>
由于 swagger 默认提供的页面实在是不敢恭维,所以就有了 swagger-ui 。
2. 配置 Swagger2
我们还是在 Spring Boot 整合 Mybatis 的基础上整合 Swagger2 进行使用。
创建 SwaggerConfig
配置类配置 Swagger :
@Configuration
@EnableSwagger2
public class SwaggerConfig {
@Bean
public Docket buildDocket() {
return new Docket(DocumentationType.SWAGGER_2)
.apiInfo(buildApiInfo())
.select()
.apis(RequestHandlerSelectors.basePackage("com.demo.swagger.controller"))
.paths(PathSelectors.any())
.build();
}
/**
* api文档介绍信息
*
* @return
*/
private ApiInfo buildApiInfo() {
return new ApiInfoBuilder()
.title("Swagger2 测试 RESTful Api 文档")
.contact(new Contact("NekoChips", "https://chenyangjie.com.cn", "shupian421182@outlook.com"))
.version("v1.0")
.build();
}
}
配置文件中需要注意的就是
apis
配置的是 swagger 扫描路径,不要填错了!
3. Swagger 注解
Swagger2 提供了非常方便的注解:
@Api
:添加在Controller
类上,用于描述Controller
。@ApiOperation
:添加在Controller
方法上,由于描述方法的功能。@ApiModel
:添加在实体类上,用于接收@ApiParam
参数。@ApiParam
:描述实体类中的参数。@ApiResponse
:描述单个请求响应。@ApiResponses
:描述多个请求响应,即包含多个@ApiResponse
。@ApiImplicitParam
:添加在 Controller 方法上,用于描述单个请求参数。@ApiImplicitParams
:描述多个请求参数,即包含多个@ApiImplicitParam
。@ApiIgnore
:忽略该 API 。@ApiError
:添加在Controller
的方法上,用于描述执行方法错误时返回的信息。
4. 使用 Swagger
在实体类中使用 Swagger:
@ApiModel(value = "学生信息")
public class Student implements Serializable {
private static final long serialVersionUID = 6029454568343571843L;
@ApiParam(value = "学生 id")
private String studentId;
@ApiParam(value = "学生姓名")
private String name;
@ApiParam(value = "学生性别")
private String sex;
// 省略 setter、getter、toString
}
在 Controller 中使用 Swagger :
@Api(tags = "学生 Controller")
@RestController
@RequestMapping("/api")
public class StudentController {
@Autowired
private IStudentService studentService;
@ApiOperation(value = "新增学生信息", notes = "根据学生实体创建学生对象")
@ApiImplicitParam(name = "student", value = "学生信息", required = true, dataTypeClass = Student.class)
@PostMapping("/student")
public HttpEntity<?> add(@RequestBody Student student) {
int count = studentService.add(student);
return count > 0 ?
ResponseEntity.ok("add student success") :
ResponseEntity.of(Optional.of("add student fail"));
}
@ApiOperation(value = "删除学生信息", notes = "根据学生id删除学生信息")
@ApiImplicitParam(name = "studentId", value = "学生id", required = true, dataTypeClass = String.class)
@DeleteMapping("student")
public HttpEntity<?> delete(String studentId) {
int count = studentService.delete(studentId);
return count > 0 ?
ResponseEntity.ok("delete student success") :
ResponseEntity.of(Optional.of("delete student fail"));
}
@ApiOperation(value = "更新学生信息", notes = "根据学生id,更新用户信息")
@ApiImplicitParams(value = {
@ApiImplicitParam(name = "studentId", value = "学生id", required = true, dataType = "String", paramType =
"path"),
@ApiImplicitParam(name = "student", value = "学生信息", required = true, dataType = "Student")
})
@PutMapping("/student/{studentId}")
public HttpEntity<?> update(@PathVariable("studentId") String studentId, @RequestBody() Student student) {
student.setStudentId(studentId);
int count = studentService.update(student);
return count > 0 ?
ResponseEntity.ok("update student success") :
ResponseEntity.of(Optional.of("update student fail"));
}
@ApiOperation(value = "查询学生信息", notes = "根据学生id查询学生信息")
@ApiImplicitParam(name = "studentId", value = "学生id", required = true, dataType = "String")
@GetMapping("student/{studentId}")
public HttpEntity<?> queryById(@PathVariable String studentId) {
Student student = studentService.queryById(studentId);
return ResponseEntity.ok(student);
}
@ApiOperation(value = "查询学生列表", notes = "查询学生列表")
@GetMapping("students")
public HttpEntity<?> queryList() {
List<Student> students = studentService.queryList();
return ResponseEntity.ok(students);
}
@ApiIgnore
@GetMapping("test")
public HttpEntity<?> test() {
return ResponseEntity.ok("Hello, this is a test!");
}
}
5. 测试
启动项目后访问 http://localhost:8080/swagger-ui.html 进入生成的 Swagger Api 文档页面。
测试 Api 接口:
6. Knife4j
以为这就完了?不,还没有,这里还要给大家推荐一款更加强大的 RESTFul API 文档生成工具 Knife4j。
Knife4j
是 Swagger-Bootstrap-UI
的升级版,界面更加清晰,还额外提供了诸多功能。先展示一下另一个项目的 Knife4j 页面。
7. Spring REST Docs
Spring 也有一套非常优秀的 RESTFul API 文档的工具,这是一款基于 Junit 测试的 API 文档生成工具,需要一定的学习成本。这里只是提一下,有兴趣地可以自行研究。
源码地址:https://github.com/NekoChips/SpringDemo/tree/master/05.springboot-swagger2
关于作者:NekoChips
本文地址:https://chenyangjie.com.cn/articles/2020/04/26/1587874999744.html
版权声明:本篇所有文章仅用于学习和技术交流,本作品采用 BY-NC-SA 4.0 许可协议,如需转载请注明出处!
许可协议:
