Spring Boot集成Swagger2 生成API文档

开始

新建springboot工程,springboot 版本为 2.1.3 ,Swagger2 版本为2.9.2

添加依赖

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
<dependencies>

<!--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>
<!--Swagger相关-->

</dependencies>

swagger 配置

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
@EnableSwagger2
@Configuration
public class SwaggerConfig {
@Bean
public Docket api() {
return new Docket(DocumentationType.SWAGGER_2)
.apiInfo(apiInfo())
.pathMapping("/")
.select() // 选择那些路径和api会生成document
// 对所有api进行监控
.apis(RequestHandlerSelectors.any())
//不显示错误的接口地址 //错误路径不监控
.paths(Predicates.not(PathSelectors.regex("/error.*")))
// 对根下所有路径进行监控
.paths(PathSelectors.regex("/.*"))
.build();
}

private ApiInfo apiInfo() {
return new ApiInfoBuilder().title("接口文档")
.contact(new Contact("Felix", "", "xxx@qq.com"))
.description("SWAGGER_2生成的接口文档")
.termsOfServiceUrl("NO terms of service")
.license("The Apache License, Version 2.0")
.licenseUrl("http://www.apache.org/licenses/LICENSE-2.0.html")
.version("v1.0")
.build();
}
}

相关注解

@Api 主要用在类上

1
2
@Api(value = "用户接口",description = "用户相关api")
public class UserController {}

@ApiOperation 主要用在方法上 其中value简短的叙述,notes一般是该方法的详细描述

1
@ApiOperation(value = "登录",notes = "登录接口")

@ApiImplicitParam 注解用于前端传入的参数
当有多个参数时,需要用@ApiImplicitParams将@ApiImplicitParam包起来
使用ApiImplicitParam时,需要指定paramType,这样也便于swagger ui 生成参数的输入格式
paramType: path, query, body, header, form
dataType: 默认String
defaultValue:参数的默认值

1
2
@ApiImplicitParams({@ApiImplicitParam(name = "username", value = "用户名"),
@ApiImplicitParam(name = "password", value = "密码")})

@ApiParam

@ApiModel

1
2
3
4
@ApiModel(value = "User", description = "用户对象")
public class User {

}

@ApiModelProperty

1
2
@ApiModelProperty(value = "ID")
private Integer id;

@ApiResponses、@ApiResponse:方法返回值的说明

1
2
3
4
@ApiResponses({
@ApiResponse(code = 400, message = "请求参数没填好"),
@ApiResponse(code = 404, message = "请求路径不对")
})

参考swagger官方注解文档:http://docs.swagger.io/swagger-core/apidocs/index.html

参考

官方文档
swagger2

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值