Swagger的注解,让我焦急

本文最后更新于:3 年前

yande.re366545akabeisoft3akizora_momijidressgame_cginochi_no_spareshukugawa_meguri.png

前几天和我一起搞项目的前端项目,因为前后端对接接口的问题吵了一架。两个脾气这么好的同志竟然找起来了 (>﹏<)

可见一个好的Swagger注解,对生命健康是多么重要 ┗|`O′|┛ 嗷~~

以下是我自己整理的常用的注解和使用方法 (~ ̄(OO) ̄)ブ

添加

1
2
3
4
5
6
7
8
9
10
11
12
13
<!--swagger2-->
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger2</artifactId>
<version>2.9.2</version>
</dependency>
<!--swagger-ui-->
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger-ui</artifactId>
<version>2.9.2</version>
</dependency>

SwaggerConfig.java文件

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
package com.books.bookshelf.middle.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;

@Configuration
@EnableSwagger2
public class SwaggerConfig {

/**
* 创建API应用
* apiInfo() 增加API相关信息
* 通过select()函数返回一个ApiSelectorBuilder实例,用来控制哪些接口暴露给Swagger来展现,
* 本例采用指定扫描的包路径来定义指定要建立API的目录。
*
* @return
*/
@Bean
public Docket createRestApi() {
return new Docket(DocumentationType.SWAGGER_2)
.apiInfo(apiInfo())
.select()
.apis(RequestHandlerSelectors.basePackage("com.books.bookshelf.middle.controller"))
.paths(PathSelectors.any())
.build();
}

/**
* 创建该API的基本信息(这些基本信息会展现在文档页面中)
* 访问地址:http://项目实际地址/swagger-ui.html
*
* @return
*/
private ApiInfo apiInfo() {
return new ApiInfoBuilder()
.title("测试 APIs")
.description("测试api接口文档(还没写)")
.termsOfServiceUrl("http://www.baidu.com")
.version("1.0")
.build();
}
}

实体类

@ApiModel(“”)

作用于实体类级别

@ApiModelProperty(“”)

作用于实体类属性级别

示例

1
2
3
4
5
6
7
@ApiModel("书单实体类")
public class BookIsbnEntity implements Serializable {

@ApiModelProperty("主键,自增")
private Integer bookId;
......
}

Controller

@Api(description = “”)

作用于Controller类级别

@ApiParam(“”)

作用于属性级别

@ApiOperation(“”)

作用于方法级别,用于描述一个Swagger operation。

说明

1
2
3
4
5
6
7
8
9
10
@Api(description = "书籍记录信息")
public class BookListController {

@ApiOperation(value ="跟据booklist的id查询实体类")
public R info(@ApiParam("书籍主键ID")@PathVariable("bookListId") Integer bookListId){
BookListEntity bookList = bookListService.getById(bookListId);

return R.ok().put("bookList", bookList);
}
}

参考

使用 Swagger 注解 - ServiceComb Java Chassis 开发指南

swagger常用注解和获取请求参数注解_幽雅兔的博客-CSDN博客

swagger注释API详细说明 - 胖陀螺的春天 - 博客园 (cnblogs.com)


本博客所有文章除特别声明外,均采用 CC BY-SA 4.0 协议 ,转载请注明出处!