Api接口文档生成工具:Swagger2
Swagger2 可以动态生成Api接口文档,使得api接口一目了然。
1. SpringBoot 整合 Swagger2
- pom.xml 导入依赖
<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>
|
- 配置类编写
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.service.Contact; import springfox.documentation.spi.DocumentationType; import springfox.documentation.spring.web.plugins.Docket; import springfox.documentation.swagger2.annotations.EnableSwagger2;
@Configuration @EnableSwagger2 public class Swagger2{ @Bean public Docket customDocket() { return new Docket(DocumentationType.SWAGGER_2) .apiInfo(apiInfo()) .select() .apis(RequestHandlerSelectors.any()) .paths(PathSelectors.any()) .build(); }
private ApiInfo apiInfo() { Contact contact = new Contact("x2yu", "x2yu.cn", "374439529@qq.com"); return new ApiInfoBuilder() .title("Api接口") .description("包含前后端的接口一览") .contact(contact) .version("1.1.0") .build(); } }
|
- Api 接口编写
例子
@GetMapping("{id}") @ApiOperation("根据id获取书籍信息") @ApiImplicitParam(name="id",value = "书籍id",required = true,dataType = "Integer") public TblBookInfo getBookById(@PathVariable("id") Integer id){ return bookInfoService.getById(id); }
@GetMapping("list/latest") @ApiOperation("获取首页最新展示书籍信息") public List<TblBookInfo> getHomeBooks(){ return bookInfoService.getHomeBooks(); }
|
上面只是非常简单的注解了一下,还有很多注解没用到
2. 项目中常用的注解说明
注解 |
属性 |
值 |
备注 |
@Api |
value |
字符串 |
可用在class 头上,class 描述 |
|
description |
字符串 |
|
|
|
|
@Api (value = “xxx”, description = “xxx”) |
@ApiOperation |
value |
字符串 |
可用在方法头上.参数的描述容器 |
|
notes |
字符串 |
|
|
|
|
@ApiOperation (value = “xxx”, notes = “xxx”) |
@ApiImplicitParams |
{} |
@ApiImplicitParam 数组 |
可用在方法头上.参数的描述容器 |
|
|
|
@ApiImplicitParams ({@ApiImplicitParam1 ,@ApiImplicitParam2 ,…}) |
@ApiImplicitParam |
name |
字符串 与参数命名对应 |
可用在@ApiImplicitParams 里 |
|
value |
字符串 |
参数中文描述 |
|
required |
布尔值 |
true/false |
|
dataType |
字符串 |
参数类型 |
|
paramType |
字符串 |
参数请求方式:query/path |
|
|
|
query:对应@RequestParam ?传递 |
|
|
|
path: 对应@PathVariable {}path传递 |
|
defaultValue |
字符串 |
在api测试中默认值 |
|
|
|
用例参见项目中的设置 |
@ApiResponses |
{} |
@ApiResponse 数组 |
可用在方法头上.参数的描述容器 |
|
|
|
@ApiResponses ({@ApiResponse1 ,@ApiResponse2 ,…}) |
@ApiResponse |
code |
整形 |
可用在@ApiResponses 里 |
|
message |
字符串 |
错误描述 |
|
|
|
@ApiResponse (code = 200, message = “Successful”) |
在配置好api后可以启动项目
访问 http://localhost:8080/swagger-ui.html
具体端口号看你的配置,页面显示大概如下
