Maven
除必需依赖外,仍需要 sping annotation 等包来完成配置
1 2 3 4 5 6 7 8 9 10 11 12
| <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>
|
使用
1. 配置类
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 45 46 47 48 49
| @Configuration @EnableSwagger2 public class SwaggerConfig {
@Bean public Docket createRestApi() { ParameterBuilder ticketPar = new ParameterBuilder(); List<Parameter> pars = new ArrayList<>(); ticketPar.name("Authorization") .description("token") .modelRef(new ModelRef("string")) .parameterType("header") .defaultValue("Bearer ") .required(true) .build(); pars.add(ticketPar.build()); return new Docket(DocumentationType.SWAGGER_2) .apiInfo(apiInfo()) .groupName("data-visual-client") .select() .apis(RequestHandlerSelectors.basePackage("com.common.controller")) .paths(PathSelectors.any()) .build() .globalOperationParameters(pars); }
public ApiInfo apiInfo() {
Contact contact = new Contact("Glett","https://www.baidu.com/","google@gmail.com");
return new ApiInfoBuilder().title("数据可视化分析平台-接口文档") .description("提供数据可视化分析平台下所有子模块的所有接口") .version("v1.0") .termsOfServiceUrl("https://www.baidu.com/") .contact(contact) .license("Apache 2.0") .licenseUrl("https://www.apache.org/licenses/LICENSE-2.0") .build(); }
}
|
2. 注解
@Api : 用在请求的类上, 表示对类的说明
tags : 说明该类的作用, 非空时将覆盖 value 的值
value : 描述类的作用
@ApiOperation : 用在请求的方法上, 说明方法的用途、作用
tags : 操作标签, 非空时将覆盖value的值
value : 操作标签, 非空时将覆盖value的值
notes : 方法的备注说明
httpMethod : 指定 HTTP 方法
response : 响应类型, 即返回对象
@ApiImplicitParams : 用在请求的方法上, 表示一组参数说明
@ApiImplicitParam : 用在 @ApiImplicitParams 注解中, 指定一个请求参数的各个方面
name : 参数名
value : 参数的说明、解释
required : 参数是否必须传
paramType : 参数放在哪个地方
header : 请求参数的获取用 @RequestHeader
query : 请求参数的获取用 @RequestParam
path : 请求参数的获取用 @PathVariable
body
form
dataType : 参数类型, 默认 string
defaultValue : 参数的默认值
@ApiResponses : 用在请求的方法上, 表示一组响应
@ApiResponse : 用在 @ApiResponses 中, 一般用于表达一个错误的响应信息
code : 数字, 例如400
message : 信息, 例如”请求参数没填好”
response : 抛出异常的类
@ApiModel : 用于响应类上, 表示一个返回响应数据的信息, 一般用在 post 创建的时候, 使用 @RequestBody 这样的场景, 请求参数无法使用 @ApiImplicitParam 注解进行描述时
@ApiModelProperty : 用在属性上, 描述响应类的属性
1 2 3 4 5
| @ApiImplicitParams({ @ApiImplicitParam(name = "userName", paramType = "query", dataType = "string", value = "用户名"), @ApiImplicitParam(name = "currentPage", paramType = "query", dataType = "int", defaultValue = "1", value = "当前页"), @ApiImplicitParam(name = "pageSize", paramType = "query", dataType = "int", defaultValue = "10", value = "每页数量"), })
|