Swagger说明
swagger是当下比较流行的实时接口文文档生成工具。
swagger官网:https://swagger.io/docs/
官网文档地址:https://github.com/swagger-api/swagger-core/wiki/Annotations
集成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>
添加配置类:
package com.xgss.demo.config;
import org.springframework.beans.factory.annotation.Value;
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 SwaggerConfiguration {
/**
* 标题
*/
@Value("${swagger.title}")
private String title;
/**
* 基本包
*/
@Value("${swagger.base.package}")
private String basePackage;
/**
* 描述
*/
@Value("${swagger.description}")
private String description;
/**
* URL
*/
@Value("${swagger.url}")
private String url;
/**
* 版本
*/
@Value("${swagger.version}")
private String version;
@Bean
public Docket createRestApi() {
return new Docket(DocumentationType.SWAGGER_2)
.apiInfo(apiInfo())
.select()
.apis(RequestHandlerSelectors.basePackage(basePackage))
.paths(PathSelectors.any())
.build();
}
private ApiInfo apiInfo() {
return new ApiInfoBuilder()
.title(title)
.description(description)
.termsOfServiceUrl(url)
.version(version)
.build();
}
}
添加配置
swagger:
enable: true
base:
package: com.xgss.demo
description: 'mybatis-plus'
title: 'mybatis-plus-demo接口文档'
url: ''
version: 2.0
添加注解
@RestController
@RequestMapping("order")
@Api("订单")
public class OrderController {
@Resource
private OrderService orderService;
@ApiOperation(value="订单保存",httpMethod = "POST")
@PostMapping("save")
public void save(){
Order order=new Order();
order.setOrderId(System.currentTimeMillis());
order.setAge(10);
order.setName("xgss");
orderService.save(order);
}
}
启动
访问:http://localhost:8080/swagger-ui.html
swagger-bootstrap-ui
使用这个ui可以使文档的另一种表现方式(可以和官网的ui方式一起使用)
引入依赖
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger2</artifactId>
<version>2.9.2</version>
</dependency>
<dependency>
<groupId>com.github.xiaoymin</groupId>
<artifactId>swagger-bootstrap-ui</artifactId>
<version>1.9.6</version>
</dependency>
swagger-bootstrap-ui默认访问地址是:http://${host}:${port}/doc.html
启动项目,访问:http://localhost:8004/doc.html
会看到如下界面:
定义的接口都可以在这里查看
配置类参数说明
示例:
@Configuration
@EnableSwagger2
public class SwaggerConfiguration {
/**
* 标题
*/
@Value("${swagger.title}")
private String title;
/**
* 基本包
*/
@Value("${swagger.base.package}")
private String basePackage;
/**
* 描述
*/
@Value("${swagger.description}")
private String description;
/**
* URL
*/
@Value("${swagger.url}")
private String url;
/**
* 版本
*/
@Value("${swagger.version}")
private String version;
/**
* 用于控制是否生成swagger文档
*/
@Value("${swagger.enable}")
private boolean enable;
@Bean
public Docket createRestApi() {
return new Docket(DocumentationType.SWAGGER_2)//// 指定api类型为swagger2
.enable(enable)//开发环境才会用到swagger,正式环境需要关闭swagger,一个是安全问题,还有一个是用了swagger会影响系统运行速度;
.groupName("xgss")//设置组名,页面上可以根据组名进行筛选只看指定组的
.apiInfo(apiInfo())// 用于定义api文档描述信息
.select()//使用过滤,必须先调用select方法;
//指定controller包,可以根据包路径来生成特定类的API,any方法是默认所有都有效,none方法都无效;
.apis(RequestHandlerSelectors.basePackage(basePackage))
.paths(PathSelectors.any())// any是匹配任意路径,none是都不匹配,regex是正则匹配;视图只显示过滤后的API接口信息
.build();
}
private ApiInfo apiInfo() {
return new ApiInfoBuilder()
.title(title)//文档页标题
.description(description)//文档描述/简介
.termsOfServiceUrl(url)//服务url
.version(version)//文档版本号
//联系人/作者信息
.contact(new Contact("xgss", "www.xgss.com", "[email protected]"))
//发布信息
.license("Apache 2.0 http://www.apache.org/licenses/LICENSE-2.0.html")
.build();
}
}
ApiInfo
title:文档标题
description:文档描述
version:版本号
termsOfServiceUrl:访问系统的url示例
license:发布信息
licenseUrl:发布详情查看地址
contact:联系方式
Docket说明
参考网址:https://blog.csdn.net/caoli201314/article/details/120544295
apiInfo
指定apiInfo信息(文档的一些描述信息)
enable
指定是否开启swagger功能,默认是true 开启
开发环境才会用到swagger,正式环境需要关闭swagger,一个是安全问题,还有一个是用了swagger会影响系统运行速度;
select、apis、paths
设置过滤
有些情况,我们需要指定固定包路径下的类生成API,或者根据前端用户路径请求过滤;
使用过滤,必须先调用select方法;
通过apis方法,basePackage可以根据包路径来生成特定类的API,
any方法是默认所有都有效,none方法都无效;
withClassAnnotation根据类注解,withMethodAnnotation是根据方法注解;
一般我们用的是 basePackage方法;
还有一个根据请求路径的paths方法;
一般用ant匹配路径;
any是匹配任意路径,none是都不匹配,regex是正则匹配;
groupName
设置分组
在实际项目开发中,把复杂项目划分多模块给多个小组或者多个人负责开发,所以每个小组或者个人要实现自己的分组,方便查找到API接口开发负责人,沟通和处理问题;
我们通过groupName方法可以设置组名;结合过滤条件类来进行分组
如
@Configuration
public class Swagger3Config {
/**
* 配置swagger的Docket bean
* @return
*/
@Bean
public Docket createRestApi() {
return new Docket(DocumentationType.OAS_30) // 指定swagger3.0版本
.groupName("开发组001")
.select()
.apis(RequestHandlerSelectors.basePackage("com.java1234.controller.one")) // 指定扫描的包 常用方式
.build()
.apiInfo(createApiInfo());
}
/**
* 配置swagger的Docket bean
* @return
*/
@Bean
public Docket createRestApi2() {
return new Docket(DocumentationType.OAS_30) // 指定swagger3.0版本
.groupName("开发组002")
.select()
.apis(RequestHandlerSelectors.basePackage("com.java1234.controller.two")) // 指定扫描的包 常用方式
.build()
.apiInfo(createApiInfo2());
}
/**
* 配置swagger的ApiInfo bean
* @return
*/
@Bean
public ApiInfo createApiInfo(){
return new ApiInfo("Java1234 Swagger"
,"Java1234 Api Documentation"
,"3.0"
,"http://www.java1234.vip"
,new Contact("小锋", "http://www.java1234.vip", "[email protected]")
,"Apache 2.0"
,"http://www.apache.org/licenses/LICENSE-2.0"
,new ArrayList());
}
/**
* 配置swagger的ApiInfo bean
* @return
*/
@Bean
public ApiInfo createApiInfo2(){
return new ApiInfo("Java1234 Swagger"
,"Java1234 Api Documentation"
,"3.0"
,"http://www.java1234.vip"
,new Contact("小丽", "http://www.java1234.vip", "[email protected]")
,"Apache 2.0"
,"http://www.apache.org/licenses/LICENSE-2.0"
,new ArrayList());
}
}
注解
相关注解:
@Api: 描述类/接口的主要用途
@ApiOperation: 描述方法用途
@ApiImplicitParam: 描述方法的参数
@ApiImplicitParams: 描述方法的参数(Multi-Params)
@ApiParam:请求属性
@ApiIgnore: 忽略某类/方法/参数的文档
@ApiResponses:响应集配置
@ResponseHeader: 响应头设置
@ApiModelProperty:添加和操作模型属性的数据
@Api
@Api(value = "停车场区域相关接口", description = "停车场区域信息操作API", tags = "parkArea")
我们如果想选择性的忽略某个字段,我们可以使用另一个注解: @ApiModelProperty(hidden = true)
@ApiParam(value = "用户id", required = true) 这个注解,需要注意的是,这个注解方法的参数前面
作用范围 |
API |
使用位置 |
对象属性 |
@ApiModelProperty |
用在出入参数对象的字段上 |
协议集描述 |
@Api |
用于controller类上 |
协议描述 |
@ApiOperation |
用在controller的方法上 |
Response集 |
@ApiResponses |
用在controller的方法上 |
Response |
@ApiResponse |
用在 @ApiResponses里边 |
非对象参数集 |
@ApiImplicitParams |
用在controller的方法上 |
非对象参数描述 |
@ApiImplicitParam |
用在@ApiImplicitParams的方法里边 |
描述返回对象的意义 |
@ApiModel |
用在返回对象类上 |
示例
@ApiOperation("信息软删除")
@ApiResponses({ @ApiResponse(code = CommonStatus.OK, message = "操作成功"),
@ApiResponse(code = CommonStatus.EXCEPTION, message = "服务器内部异常"),
@ApiResponse(code = CommonStatus.FORBIDDEN, message = "权限不足") })
@ApiImplicitParams({ @ApiImplicitParam(paramType = "query", dataType = "Long", name = "id", value = "信息id", required = true) })
@RequestMapping(value = "/remove.json", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
public RestfulProtocol remove(Long id) {
@Api
Api 用在类上,说明该类的作用。可以标记一个Controller类做为swagger 文档资源,使用方式:
@Api(value = "/user", description = "Operations about user")
属性名称 |
备注 |
value |
url的路径值 |
tags |
如果设置这个值、value的值会被覆盖,设置这个swagger文档菜单会显示这里设置的值 |
description |
对api资源的描述 |
basePath |
基本路径可以不配置 |
position |
如果配置多个Api 想改变显示的顺序位置 |
produces |
如"application/json, application/xml" |
consumes |
如"application/json, application/xml" |
protocols |
协议http, https, ws, wss |
authorizations |
高级特性认证时配置 |
hidden |
配置为true表示在文档中隐藏 |
@ApiModel
描述返回对象的意义,用在返回对象类上
value–表示对象名
description–描述
value–字段说明
name–重写属性名字
dataType–重写属性类型
required–是否必填
example–举例说明
hidden–隐藏
@ApiModelProperty
使用在方法,字段上,表示对model属性的说明或者数据操作更改
value–字段说明
name–重写属性名字
dataType–重写属性类型
required–是否必填
example–举例说明
hidden–隐藏
@ApiModel(value="user对象",description="用户对象user")
public class User implements Serializable{
private static final long serialVersionUID = 1L;
@ApiModelProperty(value="用户名",name="username",example="xingguo")
private String username;
@ApiModelProperty(value="状态",name="state",required=true)
private Integer state;
private String password;
private String nickName;
private Integer isDeleted;
@ApiModelProperty(value="id数组",hidden=true)
private String[] ids;
private List<String> idList;
//省略get/set
}
@ApiOperation
value="接口标题"
notes="接口描述"
tags:说明该方法的作用,参数是个数组,可以填多个。格式:tags={"作用1","作用2"},建议不使用这个参数,会使界面看上去有点乱,前两个常用
httpMethod:接口请求方式,"GET", "HEAD", "POST", "PUT", "DELETE", "OPTIONS" , "PATCH"
consumes:对请求的content-type的说明,application/json, application/xml,multipart/form-data等
举例:
@ApiOperation(value = "接口标题", notes = "接口描述")
test(){
}
@ApiIgnore
用于类或者方法上,可以不被swagger显示在页面上
// 整个类被 Swagger 忽略
@ApiIgnore
@RestController
@RequestMapping(value = "/xttblog")
public class XttblogController {}
@RestController
@RequestMapping(value = "/xttblog")
public class XttblogController {
// 整个方法被忽略
@ApiIgnore
public String hello(){
return "hello";
}
// Swagger 上 忽略 User 参数
public String sayHello(@ApiIgnore User user){
return "hello " + user.getName();
}
}
@ApiParam
用于方法,参数,字段说明;表示对参数的添加元数据
属性名称 |
数据类型 |
默认值 |
说明 |
name |
String |
“” |
参数名称,参数名称将从 filed/method/parameter 名称中派生,但你可以覆盖它,路径参数必须始终命名为它们所代表的路径部分 |
value |
String |
“” |
参数简单描述 |
defaultValue |
String |
“” |
描述参数默认值 |
allowableValues |
String |
“” |
可接收参数值限制,有三种方式,取值列表,取值范围 |
required |
boolean |
false |
是否为必传参数, false:非必传; true:必传 |
access |
String |
“” |
参数过滤,请参阅:io.swagger.core.filter.SwaggerSpecFilter |
allowMultiple |
boolean |
false |
指定参数是否可以通过多次出现来接收多个值 |
hidden |
boolean |
false |
隐藏参数列表中的参数 |
example |
String |
“” |
非请求体(body)类型的单个参数示例 |
examples |
Example |
@Example(value = @ExampleProperty(mediaType = “”, value = “”)) |
参数示例,仅适用于请求体类型的请求 |
type |
String |
“” |
添加覆盖检测到类型的功能 |
format |
String |
“” |
添加提供自定义format格式的功能 |
allowEmptyValue |
boolean |
false |
添加将格式设置为空的功能 |
readOnly |
boolean |
false |
添加被指定为只读的能力 |
collectionFormat |
String |
“” |
添加使用 array 类型覆盖 collectionFormat 的功能 |
示例
@ApiOperation(value="获取用户信息",tags={"获取用户信息copy"},notes="注意问题点")
@GetMapping("/getUserInfo")
public User getUserInfo(@ApiParam(name="id",value="用户id",required=true) Long id,@ApiParam(name="username",value="用户名") String username) {
public ResponseEntity<User> createUser(@RequestBody @ApiParam(value = "Created user object", required = true) User user)
@ApiImplicitParam
表示单独的请求参数
属性 |
取值 |
作用 |
paramType |
|
查询参数类型 |
|
path |
以地址的形式提交数据 |
|
query |
直接跟参数完成自动映射赋值 |
|
body |
以流的形式提交 仅支持POST |
|
header |
参数在request headers 里边提交 |
|
form |
以form表单的形式提交 仅支持POST |
dataType |
|
参数的数据类型 只作为标志说明,并没有实际验证 |
|
Long |
|
|
String |
|
name |
|
接收参数名 |
value |
|
接收参数的意义描述 |
required |
|
参数是否必填 |
|
true |
必填 |
|
false |
非必填 |
defaultValue |
|
默认值 |
@ApiImplicitParams
用于方法,包含多个 @ApiImplicitParam
实例:
@ApiImplicitParams({
@ApiImplicitParam(name="mobile",value="手机号",required=true,paramType="form"),
@ApiImplicitParam(name="password",value="密码",required=true,paramType="form"),
@ApiImplicitParam(name="age",value="年龄",required=true,paramType="form",dataType="Integer")
})
@Profile
@Profile({"dev", "test"}):用于配置类上,表示只对开发和测试环境有用
Swagger其他
不能使用继承来覆盖原文档的属性
如果页面显示了不是自己定义的vo中的东西,修改下
屏蔽掉swagger
swagger的配置文件中添加开关配置
配置文件中添加配置
true代表打开,false代表关闭