我的博客:兰陵笑笑生,欢迎浏览博客!
上一章 SpringBoot入门实践(七)-Spring-Data-JPA实现数据访问当中,我们介绍了如何在项目中使用 Spring Data JPA来进行数据库的访问。本章将继续探索springBoot的其他功能,如何快速高效的构建在线的API文档。
一 、前言
如今前后端分离,那么在前后端对接的时候少不了接口的文档,过去我们都是手写一个wold文档,我相信作为一个写代码的,最不愿意的就是写各类的文档。当然接口文档是必须的。但是我们手动维护的API文档在效率方面的确比较慢。而且还容易出错,最最要命的是随着项目的迭代,接口在不断的改变,实时的更新接口文档,是一件很分神的事情,今天我们就简单的介绍一个如何使用Swagger2快速的生成在线文档。
二、 简介
在Swagger的官方网站上https://swagger.io/ 是这样据介绍的,Swagger是实现了OpenApi标准的文档使用工具,包含了各种开源的工具集。
- Swagger Core 用于生成Swagger的API规范的事例
- Swagger UI 生成一个界面,我们这里就会用到。
- SwaggerHub API设计和文档化
- …
三 、快速上手
3.1 引入依赖
在构建好Restful API 后,我们首先在pom.xml文件中引入Swagger2和Swagger UI的依赖:
<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>
3.2 Swagger2的配置
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
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.Contact;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2;
@Configuration
@EnableSwagger2
public class Swagger2Conf {
/**
* 控制http://localhost:8081/swagger-ui.html#/的显示
* @return
*/
@Bean
public Docket controllerApi() {
return new Docket(DocumentationType.SWAGGER_2)
.apiInfo(new ApiInfoBuilder()
.title("标题:某公司_接口文档")
.description("描述:用于XXXX功能,具体包括XXX,XXX模块...")
.contact(new Contact("Socks", null, null))
.version("版本号:1.0")
.build())
.select()
//选择的包名
.apis(RequestHandlerSelectors.basePackage("com"))
.paths(PathSelectors.any())
.build();
}
}
3.3 访问地址
- http://localhost:8081/swagger-ui.html#/ 是如下的界面
- http://localhost:8081/v2/api-docs 是返回的接口的json
到这里,swagger2的应用可以说快速的入门,可以使用了,但是我们可能需要对Controller、方法做一些说明,我们可以通过以下额API精细化管理可以实现。
3.4 API精细化管理
首先的介绍几个常用的注解:
3.4.1 @Api :添加在Controller控制器上,用来解释当前的控制器
-
value:貌似没什么用
-
tags:描述这个控制器的,
-
protocols:协议类型:http
-
hidden:没什么用
@Api(value = "value", tags = "用戶管理", hidden = true) @RestController @RequestMapping("/api/v1/user") public class UserController { .... }
3.4.2 @ApiOperation:注解添加在方法上,用来解释当前的方法,包括用户返回值
- value api的解释
- notes api的注意事项
- response 返回的类型等
3.4.3 @ApiIgnore: 作用在REST API控制器方法上,则该API不会被显示出来:
@ApiOperation(value = "删除列表", notes = "注意", response = HttpResponse.class)
@ApiIgnore
@DeleteMapping("/delete/{id}")
public HttpResponse delete(@PathVariable Long id) {
userMap.remove(id);
return HttpResponse.ok();
}
3.4.4 @ApiImplicitParams和@ApiImplicitParam ,用来解释方法的参数,
@ApiImplicitParams是可以包含多个@ApiImplicitParam,如
/**
* 列表请求
* @return
*/
@ApiOperation(value = "用户列表",notes = "注意",response = HttpResponse.class)
@RequestMapping(path = "/list",method = RequestMethod.PUT,
consumes = "application/json")
@ApiImplicitParams({
@ApiImplicitParam(name="userName",value = "用戶名称"),
@ApiImplicitParam(name="age",value = "用戶年龄")
})
public HttpResponse list(String userName ,Integer age) {
List<User> user = new ArrayList<>(userMap.values());
return HttpResponse.ok().setData(user);
}
这样API文档就丰富了很多:
3.4.5 POJO 对象解释
在生成的在线API文档中,很多时候我们需要对POJO中的字段做一些解释,比如下图的User添加一个描述,对每个字段添加一个描述,以及他的类型做一个解释,这里当然也可使用Swagger2的其他2个注解:@ApiModel和 @ApiModelProperty,没有使用注解的时候如下图:
3.4.5.1 : @ApiModel 添加在POJO 类上
- value:默认是类名
- description:对当前的POJO的描述
3.4.5.1:@ApiModelProperty
- name:属性,默认pojo属性
- value:值
- nodtes:注意事项
- dataType:属性类型
- required:是否必须
- allowEmptyValue :是否允许空置
- allowableValues :允许的值
package com.miroservice.chapter2.pojo;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
@ApiModel(value = "user",description = "用户")
public class User {
@ApiModelProperty(value = "用户ID",notes = "notes",dataType = "long",required = false,allowEmptyValue = true)
private Long id;
@ApiModelProperty(value ="用户名称",notes = "notes",dataType = "String",required = false,allowEmptyValue = true)
private String userName;
@ApiModelProperty("用户年齡")
private Long age;
...
}
这样保存的用户的每个属性都有了解释:
3.5 生产环境关闭Swagger2
我们使用Swagger2是为了方便开发,但是如在把这样的文档在生产环境开启,那我估计过不了多久工作就没了,如何才能在正式环境禁止使用Swagger2呢,其实很简单。我们可以在配置swagger的使用,添加一个注解:
@ConditionalOnProperty,并通过配置文件配置swagger.enable=true的时候,才开启swagger,如下配置:
@Configuration
@EnableSwagger2
@ConditionalOnProperty(name = "swagger.enable", havingValue = "true")
public class Swagger2Conf {
/**
* 控制http://localhost:8081/swagger-ui.html#/的显示
* @return
*/
@Bean
public Docket controllerApi() {
return new Docket(DocumentationType.SWAGGER_2)
.apiInfo(new ApiInfoBuilder()
.title("标题:某公司_接口文档")
.description("描述:用于XXXX功能,具体包括XXX,XXX模块...")
.contact(new Contact("Socks", null, null))
.version("版本号:1.0")
.build())
.select()
//选择的包名
.apis(RequestHandlerSelectors.basePackage("com"))
.paths(PathSelectors.any())
.build();
}
}
四 、总结
这一篇文章简单的介绍了springBoot如何集成Swagger2快速的构建在线的API文档,包括各种注解的详细的解释,当然Swagger2的强大之处不仅于此,还提供了更多扩展的功能,包括API分组,为每个API配置Token,生成静态的文档等,有兴趣的可以自己深入研究,本章的介绍对于平时的开发应该是够用了。
以上就是本期的分享,你还可以关注本博客的#Spring Boot入门实践系列!#
本文由博客一文多发平台 OpenWrite 发布!