Swagger2使用小结
接口文档贯穿整个项目的开发流程,接口文档在定义、流转和后期维护中费时费力,Swagger的出现可以完美解决以上传统接口管理方式存在的痛点
使用流程:
- 引入maven依赖
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger2</artifactId>
<version>2.6.1</version>
</dependency>
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger-ui</artifactId>
<version>2.6.1</version>
</dependency>
- 编写Swagger2配置类
@Configuration // 配置注解,自动在本类上下文加载一些环境变量信息
@EnableSwagger2 // 使swagger2生效
public class SwaggerConfig {
@Bean
public Docket swaggerSpringMvcPlugin() {
return new Docket(DocumentationType.SWAGGER_2)
.apiInfo(apiInfo()) //api的标题、描述、版本等信息
.groupName("express-material-api") //接口模块名称
.select() // 选择那些路径和api会生成document
.apis(RequestHandlerSelectors
.basePackage("com.best.oasis.settlement.web.controller"))
.paths(PathSelectors.any())
.build();
}
private ApiInfo apiInfo() {
return new ApiInfoBuilder()
.title("物料系统RESTful API")
.termsOfServiceUrl("http://localhost:8080/")
.description("此API提供接口调用")
.license("License Version 1.0")
.version("1.0").build();
}
}
- 整合springMVC 配置swagger-ui.html
<mvc:resources mapping="swagger-ui.html" location="classpath:/META-INF/resources/"/>
<mvc:resources mapping="/webjars/**" location="classpath:/META-INF/resources/webjars/"/>
<bean class="com.xxx.xxx.xxx..config.SwaggerConfig"></bean>
- 常用注解说明
@Api:用在请求的类上,表示对类的说明
tags="说明该类的作用,可以在UI界面上看到的注解"
value="该参数没什么意义,在UI界面上也看到,所以不需要配置"
@ApiOperation:用在请求的方法上,说明方法的用途、作用
value="说明方法的用途、作用"
notes="方法的备注说明"
@ApiImplicitParams:用在请求的方法上,表示一组参数说明
@ApiImplicitParam:用在@ApiImplicitParams注解中,指定一个请求参数的各个方面
name:参数名
value:参数的汉字说明、解释
required:参数是否必须传
paramType:参数放在哪个地方
· header --> 请求参数的获取:@RequestHeader
· query --> 请求参数的获取:@RequestParam
· path(用于restful接口)--> 请求参数的获取:@PathVariable
· body(不常用)
· form(不常用)
dataType:参数类型,默认String,其它值dataType="Integer"
defaultValue:参数的默认值
@ApiResponses:用在请求的方法上,表示一组响应
@ApiResponse:用在@ApiResponses中,一般用于表达一个错误的响应信息
code:数字,例如400
message:信息,例如"请求参数没填好"
response:抛出异常的类
@ApiModel:用于响应类上,表示一个返回响应数据的信息
(这种一般用在post创建的时候,使用@RequestBody这样的场景,
请求参数无法使用@ApiImplicitParam注解进行描述的时候)
@ApiModelProperty:用在属性上,描述响应类的属性
- 使用方法
直接在对应的Controller、方法名、实体类上加上对应注解即可 - 呈现效果