一、为什么要使用Swagger生成文档?
使用 Swagger 集成文档具有以下几个优势:
- 功能丰富 :支持多种注解,自动生成接口文档界面,支持在界面测试API接口功能;
- 及时更新 :开发过程中花一点写注释的时间,就可以及时的更新API文档,省心省力;
- 整合简单 :通过添加pom依赖和简单配置,内嵌于应用中就可同时发布API接口文档界面,不需要部署独立服务。
二、Swagger生成文档步骤:
1、生成项目模板
为方便我们初始化项目,Spring Boot给我们提供一个项目模板生成网站。
(1)、打开浏览器,访问:https://start.spring.io/
(2)、根据页面提示,选择构建工具,开发语言,项目信息等。
2、添加swagger 相关依赖
<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、添加配置类
package com.example.demo.config; 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; /** * Swagger API文档配置类 */ @Configuration @EnableSwagger2 public class SwaggerConfig { @Bean public Docket restfulApi() { return new Docket(DocumentationType.SWAGGER_2) .apiInfo(apiInfo()) .select() .apis(RequestHandlerSelectors.any()) .paths(PathSelectors.any()) .build(); } private ApiInfo apiInfo() { return new ApiInfoBuilder() .title("API 文档标题") .description("API 文档描述") .version("1.0.0") .build(); } }
4、API 文档代码
package com.example.demo.controller; import io.swagger.annotations.*; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.ui.ModelMap; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RestController; import java.time.LocalDate; @Api(value = "类描述") @RestController public class HelloController { private final Logger logger = LoggerFactory.getLogger(HelloController.class); @ApiOperation(value = "初次见面", notes = "世界您好!") @GetMapping("/") public String home() { return "Hello World!"; } @ApiOperation(value = "向你问好", notes = "hello <名字>") @GetMapping("/hello") public String hello(@ApiParam(value = "打招呼名字", required = true) @RequestParam String name) { return "Hello " + name + "!"; } @ApiOperation(value = "查询车辆接口", notes = "此接口描述xxxxxxxxxxxxx<br/>xxxxxxx<br>值得庆幸的是这儿支持html标签<hr/>", response = String.class) @ApiImplicitParams({ @ApiImplicitParam(name = "vno", value = "车牌", required = false, dataType = "string", paramType = "query", defaultValue = "辽A12345"), @ApiImplicitParam(name = "page", value = "page", required = false, dataType = "Integer", paramType = "query", defaultValue = "1"), @ApiImplicitParam(name = "count", value = "count", required = false, dataType = "Integer", paramType = "query", defaultValue = "10") }) @ApiResponses(value = { @ApiResponse(code = 200, message = "Successful — 请求已完成"), @ApiResponse(code = 400, message = "请求中有语法问题,或不能满足请求"), @ApiResponse(code = 401, message = "未授权客户机访问数据"), @ApiResponse(code = 404, message = "服务器找不到给定的资源;文档不存在"), @ApiResponse(code = 500, message = "服务器不能完成请求")} ) @GetMapping("/vehicles") public ModelMap findVehicles(@RequestParam(value = "vno", required = false) String vno, @RequestParam(value = "page", required = false) Integer page, @RequestParam(value = "count", required = false) Integer count) throws Exception { logger.info("http://localhost:8501/api/v1/vehicles"); logger.info("## {},{},{}", vno, page, count); logger.info("## 请求时间:{}", LocalDate.now()); ModelMap map = new ModelMap(); map.addAttribute("vno", vno); map.addAttribute("page", page); return map; } }
三、spring-boot-swagger2 在项目中常用的注解说明:
(1)、@Api: 属性 value 、description 可用在class
头上,class
描述
示例代码:
@Api(value = "类描述")
(2)、@ApiOperation: 属性 value 、notes 可用在方法头上,参数的描述容器
示例代码:
@ApiOperation(value = "向你问好", notes = "hello <名字>")
(3)、@ApiParam、@ApiImplicitParam、@ApiImplicitParams:注解API 的参数 ,也就是用于swagger提供开发者文档生成的注释内容。
@ApiParam和@ApiImplicitParam的功能是相同的,但是@ApiImplicitParam的适用范围更广。在非JAX-RS的场合(比如使用servlet提供HTTP接口),只能使用@ApiImplicitParam进行参数说明。我认为,这是因为接口并不显式展示入参的名称,所以没有地方去使用@ApiParam,只能在接口的方法声明下方写@ApiImplicitParam 。
属性说明:
- name:名字, 可用在
@ApiImplicitParams
里 - value :参数中文描述
- required: true/false , 代表是否必须传参
- dataType:参数类型
- paramType:参数请求方式, 这里有几种形式:
path 以地址的形式提交数据,对应@PathVariable
{}path传递。 query 直接跟参数完成自动映射赋值,对应@RequestParam
?传递。 body 以流的形式提交 仅支持POST ,@RequestBody header 参数在request headers 里边提交 form 以form表单的形式提交 仅支持POST
- defaultValue:可用在方法头上,参数的描述容器
@ApiImplicitParams
: @ApiImplicitParam
数组,可用在方法头上,参数的描述容器。
示例代码:
@ApiImplicitParams({ @ApiImplicitParam(name = "vno", value = "车牌", required = false, dataType = "string", paramType = "query", defaultValue = "辽A12345"), @ApiImplicitParam(name = "page", value = "page", required = false, dataType = "Integer", paramType = "query", defaultValue = "1"), @ApiImplicitParam(name = "count", value = "count", required = false, dataType = "Integer", paramType = "query", defaultValue = "10") })
4、@ApiResponses 、@ApiResponse:可用在方法头上,用作返回值的描述。
@ApiResponses 一个包装器,允许列出多个 ApiResponse,若需要描述单个 ApiResponse,你仍然必须使用此注解并将@ApiResponse 包装在一个数组中;
属性名称 | 数据类型 | 默认值 | 说明 |
value | ApiResponse[] | ApiResponse 列表 |
@ApiResponse:在 Rest 接口或类上和 @ApiResponses 组合使用,组装返回参数说明。
属性说明:
属性名称 | 数据类型 | 默认值 | 说明 |
code | int | 响应的HTTP状态码 | |
message | String | 伴随响应的人类可读的消息 | |
response | Class<?> | Void.class | 用于描述消息有效负载的可选响应类,对应于响应消息对象的 schema 字段 |
reference | String | “” | 指定对响应类型的引用,指定的应用可以使本地引用,也可以是远程引用,将按原样使用,并将覆盖任何指定的response()类 |
responseHeaders | ResponseHeader[] | @ResponseHeader(name = “”, response = Void.class) | 可能响应的 header 列表 |
responseContainer | String | “” | 声明响应的容器,有效值为List,Set,Map,任何其他值都将被忽略 |
示例代码:
@ApiResponses(value = { @ApiResponse(code = 200, message = "Successful — 请求已完成"), @ApiResponse(code = 400, message = "请求中有语法问题,或不能满足请求"), @ApiResponse(code = 401, message = "未授权客户机访问数据"), @ApiResponse(code = 404, message = "服务器找不到给定的资源;文档不存在"), @ApiResponse(code = 500, message = "服务器不能完成请求")} )