声明:本文多处直接引用了文末的参考链接中的内容,如有侵权,请联系删除
项目集成Swagger2
Swagger2的实现原理
- 项目启动,Spring初始化上下文,加载Swagger相关的Bean,并由此扫描系统中需要生成的API文档注解获取注释信息
Spring boot集成Swagger2
- 引入maven依赖
<!-- Swagger2基础依赖 -->
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger2</artifactId>
<version>3.0.0</version>
</dependency>
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger-ui</artifactId>
<version>3.0.0</version>
</dependency>
<!-- Swagger2基础依赖结束 -->
<!-- Swagger2皮肤依赖,如果只需要使用原生的Swagger文档,则不需要引入 -->
<dependency>
<groupId>com.github.xiaoymin</groupId>
<artifactId>knife4j-spring-boot-starter</artifactId>
<version>3.0.3</version>
<exclusions>
<exclusion>
<artifactId>swagger-models</artifactId>
<groupId>io.swagger</groupId>
</exclusion>
<exclusion>
<artifactId>swagger-annotations</artifactId>
<groupId>io.swagger</groupId>
</exclusion>
</exclusions>
</dependency>
<!-- Swagger2皮肤依赖结束 -->
- 编写Swagger配置文件
package com.mostall.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.service.Contact;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2;
/**
* @author sut
* @version v1.0
* @since 2021/8/28
*/
@Configuration
@EnableSwagger2
public class Swagger2Config {
// 配置swagger2核心
@Bean
public Docket creatRestApi() {
return new Docket(DocumentationType.SWAGGER_2) // 指定api类型为swagger2
// api基本信息
.apiInfo(apiInfo()) // 用于定义api文档汇总信息
// 设置允许保暴露的接口
.select()
.apis(RequestHandlerSelectors.basePackage("com.mostall.controller")) // 指定controller包
.paths(PathSelectors.any()) // 所有controller
.build();
}
private ApiInfo apiInfo() {
return new ApiInfoBuilder()
.title("api文档") // 文档标题
.description("api文档")
.contact(new Contact("mostall", "https://www.mostall.com", "seta2012@foxmail.com"))
.version("1.0.0")
.build();
}
}
- 编写静态资源拦截配置
package com.mostall.config;
import com.google.common.collect.Lists;
import com.mostall.interceptor.UserTokenInterceptor;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
import java.util.List;
/**
* web相关配置,包括资源放行,redis的相关配置信息
*
* @author sut
* @version v1.0
* @since 2021/8/28
*/
@Configuration
public class WebConfig implements WebMvcConfigurer {
/**
* 静态资源配置
*/
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
// 配置本地文件夹目录映射
// registry.addResourceHandler("/**")
// 项目中的文件目录,此处也可以直接使用项目以外的文件目录
// .addResourceLocations("file:uploads/");
// 配置其他静态资源
registry.addResourceHandler("/**")
.addResourceLocations("file:uploads/")
.addResourceLocations("classpath:/static/");
// 配置knife4j 皮肤静态资源
registry.addResourceHandler("doc.html")
.addResourceLocations("classpath:/META-INF/resources/");
// 对swagger2 ui库中的静态文件进行映射
registry.addResourceHandler("/swagger-ui/**")
.addResourceLocations("classpath:/META-INF/resources/webjars/springfox-swagger-ui/");
registry.addResourceHandler("/webjars/**")
.addResourceLocations("classpath:/META-INF/resources/webjars/");
}
}
- 在controller或者vo类上使用swagger相关注解
Swagger2常用注解说明
Api
Api 用在类上,说明该类的作用。可以标记一个Controller类做为swagger 文档资源,使用方式:
@Api(tags={"用户接口"})
与Controller注解并列使用。 属性配置:
属性名称 | 属性类型 | 备注 | 默认值 |
---|---|---|---|
value | String | url的路径值 | “” |
tags | String[] | 如果设置这个值、value的值会被覆盖。可以配置多个,当配置多个的时候,在页面中会显示多个接口的信息 | “” |
produces | String | MIME类型列表(output),如: "application/json, application/xml" | “” |
consumes | String | MIME类型列表(input),如: "application/json, application/xml" | “” |
protocols | String | 协议类型,如: http、https、ws、wss | “” |
authorizations | Authorization[] | 获取授权列表(安全声明),如果未设置,则返回一个空的授权值 | |
hidden | boolean | 是否在文档中隐藏 | false |
在SpringMvc中的配置如下:
@Controller
@RequestMapping(value = "/api/pet", produces = {APPLICATION_JSON_VALUE, APPLICATION_XML_VALUE})
@Api(value = "/pet", description = "Operations about pets")
public class PetController {
}
ApiOperation
ApiOperation用在方法上,说明方法的作用,每一个url资源的定义,使用方式:
@ApiOperation(
value = "Find purchase order by ID",
notes = "For valid response try integer IDs with value <= 5 or > 10. Other values will generated exceptions",
response = Order,
tags = {"Pet Store"})
与Controller中的方法并列使用。属性配置:
属性名称 | 属性类型 | 备注 | 默认值 |
---|---|---|---|
value | String | url的路径值 | |
notes | String | 对api资源的描述 | "" |
tags | String[] | 标签 | "" |
response | Class<?> | 响应类型(即返回对象) | Void.class |
responseContainer | String | 声明包装的响应容器(返回对象类型)。有效值为 "List", "Set" or "Map" | “” |
responseReference | String | 指定对响应类型的引用。将覆盖任何指定的response()类 | “” |
httpMethod | String | 指定HTTP方法,"GET"、"HEAD"、"POST"、"PUT"、"DELETE"、"OPTIONS"、"PATCH" | “” |
nickname | String | 第三方工具唯一标识,默认为空 | “” |
produces | String | MIME类型列表(output),如: "application/json, application/xml" | “” |
consumes | String | MIME类型列表(input),如: "application/json, application/xml" | “” |
protocols | String | 协议类型,如: http、https、ws、wss | “” |
authorizations | Authorization[] | 获取授权列表(安全声明),如果未设置,则返回一个空的授权值 | |
hidden | boolean | 是否在文档中隐藏 | false |
responseHeaders | ResponseHeader[] | 响应头列表 | |
code | int | 响应的HTTP状态代码 | 200 |
extensions | Extension[] | 扩展属性列表数组 | |
ignoreJsonView | boolean | 序列化时是否忽略 | false |
在SpringMvc中的配置如下:
@RequestMapping(value = "/order/{orderId}", method = GET)
@ApiOperation(
value = "Find purchase order by ID",
notes = "For valid response try integer IDs with value <= 5 or > 10. Other values will generated exceptions",
response = Order.class,
tags = { "Pet Store" })
public ResponseEntity<Order> getOrderById(@PathVariable("orderId") String orderId)
throws NotFoundException {
Order order = storeData.get(Long.valueOf(orderId));
if (null != order) {
return ok(order);
} else {
throw new NotFoundException(404, "Order not found");
}
}
ApiParam
ApiParam用在参数中,对请求的参数进行标记,使用方式:
public ResponseEntity<User> createUser(@RequestBody @ApiParam(value = "Created user object", required = true) User user)
与Controller中的方法并列使用。属性配置:
属性名称 | 属性类型 | 备注 | 默认值 |
---|---|---|---|
name | String | 属性名称 | "" |
value | String | 属性值 | "" |
defaultValue | String | 默认属性值 | "" |
allowableValues | String | 可以不配置 | "" |
required | boolean | 是否属性必填 | false |
access | String | 不过多描述 | "" |
allowMultiple | boolean | 是否可以接受多个值 | false |
hidden | boolean | 是否在文档中隐藏 | false |
example | String | 单个示例 | "" |
examples | Example | 参数示例 | |
type | String | "" | |
format | String | "" | |
allowEmptyValue | boolean | 是否允许空值 | false |
readOnly | boolean | 是否只读 | false |
collectionFormat | String | "" |
在SpringMvc中的配置如下:
public ResponseEntity<Order> getOrderById(
@ApiParam(value = "ID of pet that needs to be fetched", allowableValues = "range[1,5]", required = true)
@PathVariable("orderId") String orderId)
ApiModel
ApiModel用在实体类上,用于对实体类参数进行说明。使用方式代码如下所示。
@ApiModel(value = "AddUserParam", description = "新增用户参数")
public class AddUserParam {
}
ApiModel通常与ApiModelProperty配合使用。属性配置:
属性名称 | 属性类型 | 备注 | 默认值 |
---|---|---|---|
value | String | 参数名称 | "" |
description | String | 参数描述 | "" |
parent | Class<?> | 父类型 | Void.class |
discriminator | String | "" | |
subTypes | Class<?>[] | 子类型 | {} |
reference | String | 指定对相应类型定义的引用,覆盖指定的任何参数值 | "" |
ApiModelProperty
ApiModelProperty() 用于字段,表示对 model 属性的说明。使用方式代码如下所示。
@Data@ApiModel(value = "com.biancheng.auth.param.AddUserParam", description = "新增用户参数")
public class AddUserParam {
@ApiModelProperty(value = "ID")
private String id;
@ApiModelProperty(value = "名称")
private String name;
@ApiModelProperty(value = "年龄")
private int age;
}
效果如图 2 右下角。
ApiModelProperty通常用在ApiModel标记的类的属性上。属性配置:
属性名称 | 属性类型 | 备注 | 默认值 |
---|---|---|---|
name | String | 属性名称 | "" |
value | String | 属性值 | "" |
allowableValues | String | 可以不配置 | "" |
access | String | 允许从API文档中过滤参数 | "" |
notes | String | 注释说明 | "" |
dataType | String | 参数类型,默认String,其它值dataType="Integer" | "" |
required | boolean | 默认为false | false |
position | int | 显示的顺序位置 | 0 |
hidden | boolean | 是否在文档中隐藏 | false |
example | String | 单个示例 | "" |
accessMode | AccessMode | AccessMode.AUTO | |
reference | String | 指定对相应类型定义的引用,覆盖指定的任何参数值 | "" |
allowEmptyValue | boolean | 是否允许空值 | false |
ApiResponse
ApiResponse:响应配置,一般用于表达一个错误的响应信息,使用方式:
@ApiResponse(code = 400, message = "Invalid user supplied")
与Controller中的方法并列使用。 属性配置:
属性名称 | 属性类型 | 备注 | 默认值 |
---|---|---|---|
code | int | http的状态码 | |
message | String | 状态码对应的响应信息 | "" |
response | Class<?> | 默认响应类 Void | Void.class |
reference | String | 指定对相应类型定义的引用,覆盖指定的任何参数值 | "" |
responseHeaders | ResponseHeader[] | 响应头列表 | |
responseContainer | String | 声明包装的响应容器(返回对象类型)。有效值为 "List", "Set" or "Map" | "" |
examples | Example | 参数示例 |
在SpringMvc中的配置如下:
@RequestMapping(value = "/order", method = POST)
@ApiOperation(value = "Place an order for a pet", response = Order.class)
@ApiResponses({ @ApiResponse(code = 400, message = "Invalid Order") })
public ResponseEntity<String> placeOrder(
@ApiParam(value = "order placed for purchasing the pet", required = true) Order order) {
storeData.add(order);
return ok("");
}
ApiResponses
ApiResponses用于表示一组配置,使用方式:
@ApiResponses({ @ApiResponse(code = 400, message = "Invalid Order") })
与Controller中的方法并列使用。 属性配置:
属性名称 | 属性类型 | 备注 | 默认值 |
---|---|---|---|
value | ApiResponse[] | 多个ApiResponse配置 |
在SpringMvc中的配置如下:
@RequestMapping(value = "/order", method = POST)
@ApiOperation(value = "Place an order for a pet", response = Order.class)
@ApiResponses({ @ApiResponse(code = 400, message = "Invalid Order") })
public ResponseEntity<String> placeOrder(
@ApiParam(value = "order placed for purchasing the pet", required = true) Order order) {
storeData.add(order);
return ok("");
}
ResponseHeader
ResponseHeader用于响应头配置,使用方法
@ResponseHeader(name="head1",description="response head conf")
与Controller中的方法并列使用。 属性配置:
属性名称 | 属性类型 | 备注 | 默认值 |
---|---|---|---|
name | String | 响应头名称 | "" |
description | String | 头描述 | "" |
response | Class<?> | 响应类型(即返回对象) | Void.class |
responseContainer | String | 声明包装的响应容器(返回对象类型)。有效值为 "List", "Set" or "Map" | "" |
在SpringMvc中的配置如下:
@ApiModel(description = "群组")
其他
ApiImplicitParam 和 ApiImplicitParams
ApiImplicitParam 和 ApiImplicitParams用于方法上,为单独的请求参数进行说明。使用方式:
@ApiImplicitParams({ @ApiImplicitParam(name = "id", value = "用户ID", dataType = "string", paramType = "query", required = true, defaultValue = "1") })
@ApiResponses({ @ApiResponse(code = 200, message = "OK", response = UserDto.class) })
@GetMapping("/user")
public UserDto getUser(@RequestParam("id") String id) {
return new UserDto();
}
ApiImplicitParam属性配置:
属性名称 | 属性类型 | 备注 | 默认值 |
---|---|---|---|
name | String | 参数名,参数名称可以覆盖方法参数名称,路径参数必须与方法参数一致 | "" |
value | String | 参数中文说明 | "" |
defaultValue | String | 参数的默认值 | "" |
allowableValues | String | 限制参数的可接受值。1、以逗号分隔的列表;2、范围值;3、设置最小值/最大值 | "" |
required | boolean | 参数是否必须传 | false |
access | String | 允许从API文档中过滤属性 | “” |
allowMultiple | boolean | 是否可以接受多个值 | false |
dataType | String | 参数类型,默认String,其它值dataType="Integer" | “” |
dataTypeClass | Class<?> | 参数数据类型 | Void.class |
paramType | String | 参数放在哪个地方,取值为header、query、path、body、form | "" |
example | String | 单个示例 | “” |
examples | Example | 参数示例 | |
type | String | “” | |
format | String | "" | |
allowEmptyValue | boolean | 是否允许空值 | false |
readOnly | boolean | 是否只读 | false |
collectionFormat | String | "" |
ApiImplicitParams属性配置:
属性名称 | 属性类型 | 备注 | 默认值 |
---|---|---|---|
value | ApiImplicitParam[] | 多个ApiImplicitParam配置 |