Swagger自动生成接口文档

1. 添加依赖

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

2. 配置Swagger

新建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
package com.pibigstar.common.config;

import io.swagger.annotations.ApiOperation;
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;

/**
* Swagger配置
* @author pibigstar
*
*/
@Configuration
@EnableSwagger2
public class SwaggerConfig{

@Bean
public Docket createRestApi() {
return new Docket(DocumentationType.SWAGGER_2)
.apiInfo(apiInfo())
.select()
//只有加了ApiOperation注解的类,才生成接口文档
.apis(RequestHandlerSelectors.withMethodAnnotation(ApiOperation.class))
//包下的类,生成接口文档
//.apis(RequestHandlerSelectors.basePackage("com.pibigstar.web"))
.paths(PathSelectors.any())
.build();
}

private ApiInfo apiInfo() {
return new ApiInfoBuilder()
.title("VIP资源解析")
.description("VIP资源解析文档")
.termsOfServiceUrl("http://mxspvip.cn")
.version("1.5.0")
.build();
}
}

3. 使用

@Api

用在类上,说明该类的作用

1
2
3
@Controller
@Api(value="VIP视频播放",tags="视频播放接口")
public class ParseVIPController extends BaseController{ }

@ApiOperation

用在方法上,说明方法的作用

1
2
3
@RequestMapping(value="/vip",method=RequestMethod.GET)
@ApiOperation("VIP视频播放")
public ModelAndView play(){}

@ApiParam

用在参数中,说明参数的作用

1
2
3
public MyResponse seach(
@ApiParam(name = "type",value = "类型1:酷狗,2:QQ",required = true)String type,
@ApiParam(name = "music",value = "音乐名",required = true)String music){ }

@ApiImplicitParams

用在方法上,用来说明方法中参数的作用

1
2
@ApiImplicitParams(value = { @ApiImplicitParam(name="url",value="视频地址")})
public ModelAndView play(String url) { }

@ApiModel

描述一个Model的信息(这种一般用在post创建的时候,使用@RequestBody这样的场景,请求参数无法使用@ApiImplicitParam注解进行描述的时候)

1
2
3
4
5
6
7
8
9
10
11
@ApiModel(value="用户信息")   
public class User {
@ApiModelProperty("用户id")
private Integer userCode;
@ApiModelProperty("用户类型")
private String userType;
@ApiModelProperty("用户名称")
private String userName;
@ApiModelProperty("用户手机号")
private String mobileNumber;
}

@ApiResponses

用在方法上,用来表示一组响应信息

@ApiResponse

用在@ApiResponses中,一般用于表达一个错误的响应信息

code:数字,例如400

message:信息,例如”请求参数没填好”

response:抛出异常的类

4. 访问

http://localhost:8080/swagger-ui.html

-------------本文结束感谢您的阅读-------------