SpringBoot-Swagger

在项目中使用Swagger

步骤

  1. 在pom引入jar包

    1. 3.0.0直接使用starter

      1
      2
      3
      4
      5
      6
      <!-- https://mvnrepository.com/artifact/io.springfox/springfox-boot-starter -->
      <dependency>
      <groupId>io.springfox</groupId>
      <artifactId>springfox-boot-starter</artifactId>
      <version>3.0.0</version>
      </dependency>
    2. 2.X.X版本

      1
      2
      3
      4
      5
      6
      7
      8
      9
      10
      11
      12
      <!-- https://mvnrepository.com/artifact/io.springfox/springfox-swagger-ui -->
      <dependency>
      <groupId>io.springfox</groupId>
      <artifactId>springfox-swagger-ui</artifactId>
      <version>3.0.0</version>
      </dependency>
      <!-- https://mvnrepository.com/artifact/io.springfox/springfox-swagger2 -->
      <dependency>
      <groupId>io.springfox</groupId>
      <artifactId>springfox-swagger2</artifactId>
      <version>3.0.0</version>
      </dependency>
  2. 配置swagger

    1. 3.0.0 直接打开http://localhost:8080/swagger-ui/index.html即可

    2. 2.X.X: 在config包下面新建一个SwaggerConfig. 使用注解开启Swagger

      1
      2
      3
      4
      5
      @Configuration
      @EnableSwagger2 // 开启
      public class SwaggerConfig {

      }

配置

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
@Configuration
public class SwaggerConfig {

// 配置了Swagger的Docket的bean实例
@Bean
public Docket docket(){
return new Docket(DocumentationType.OAS_30)
.apiInfo(apiInfo())
.groupName("yiqing") // 扫描包
.select()
// RequestHandlerSelectors 配置要扫描接口的方式
// basePackage 指定要扫描的包
// withClassAnnotation: 扫描类上的注解 RestController.class
// withMethodAnnotation: 扫描方法上的注解 GetMapping.class
.apis(RequestHandlerSelectors.basePackage("com.famesmart.controller"))
// 过滤什么路径
.paths(PathSelectors.any())
.build();
}

private ApiInfo apiInfo(){
return new ApiInfoBuilder()
.title("Tag系统api文档")
.description("目前用于SaaS项目使用")
.contact(new Contact("yiqing","www.famesmart.com","y.zhang@live.com"))
.version("1.0.0")
.build();
}
}

配置多个分组

协同开发: 配置多个docket实例,更改groupName即可

模型

1
2
3
4
5
6
7
8
9
10
@Data
@AllArgsConstructor
@NoArgsConstructor
public class Resident {
// 此项目没有修改resident的权利,遂只保留id
@ApiModelProperty("居民id")
private int id;
@ApiModelProperty("居民tag列表")
List<Tag> tags;
}

接口

说明:Api用来指定一个controller中的各个接口的通用说明

​ Operation:用来说明一个方法

​ @ApiImplicitParams:用来包含多个包含多个 @ApiImplicitParam,

​ @ApiImplicitParam:用来说明一个请求参数

​ 如果使用@Parameter来做说明,可以直接加到@RequestParam参数之前

​ @ApiIgnore:用来忽略不必要显示的参数

1
2
3
4
5
@ApiOperation("添加某tag至resident")
@ApiImplicitParams({
@ApiImplicitParam(name = "residentId", value = "居民id", dataType = "Integer", paramType = "path", example = "44"),
@ApiImplicitParam(name = "tagId", value = "tag id", dataType = "Integer", paramType = "path", example = "1")
})

可以直接在参数前面加@ApiParam(value=””,name=””)