Spring Boot 学习笔记(七) 整合 Swagger2

885 阅读7分钟

Spring Boot 学习笔记(七) 整合 Swagger2


1. 添加依赖

Swagger2 可以自动的根据代码生成接口文档。

添加依赖:

1<dependency>
2    <groupId>org.springframework.boot</groupId>
3    <artifactId>spring-boot-starter-web</artifactId>
4</dependency>
5<dependency>
6    <groupId>org.springframework.boot</groupId>
7    <artifactId>spring-boot-starter-thymeleaf</artifactId>
8</dependency>
9
10<!-- swagger api 管理工具 -->
11<dependency>
12    <groupId>io.springfox</groupId>
13    <artifactId>springfox-swagger2</artifactId>
14    <version>2.8.0</version>
15</dependency>
16<dependency>
17    <groupId>io.springfox</groupId>
18    <artifactId>springfox-swagger-ui</artifactId>
19    <version>2.8.0</version>
20</dependency>

注意需要添加:spring boot web 依赖

2. 添加Swagger配置

修改 SpringbootApplication 启动类

1@SpringBootApplication
2@EnableSwagger2
3@ComponentScan({"com.zdran.springboot"})
4public class SpringbootApplication {
5
6    public static void main(String[] args) {
7        SpringApplication.run(SpringbootApplication.class, args);
8    }
9
10    @Bean
11    public Docket createRestApi() {
12        return new Docket(DocumentationType.SWAGGER_2)
13                .apiInfo(apiInfo())
14                .select()
15                .apis(RequestHandlerSelectors.basePackage("com.zdran.springboot.controller"))
16                .paths(PathSelectors.any())
17                .build();
18    }
19
20    private ApiInfo apiInfo() {
21        return new ApiInfoBuilder()
22                .title("个人学习Spring Boot 的项目 APIs")
23                .description("学习Spring Boot 中的 restful APIs")
24                .termsOfServiceUrl("https://github.com/zdRan/learning")
25                .contact(new Contact("个人开源项目组", 
26                                    "https://github.com/zdRan/learning", 
27                                    "cm.zdran@gmail.com"))
28                .version("1.0")
29                .build();
30    }

默认访问地址是: http://localhost:9090/learning/swagger-ui.html

3. Swagger 注解

Swagger 有很多自定义的注解可以很方便的对接口进行描述

3.1 @Api

用在一个Controller上,swagger会将这个controller下的接口归为一组展示。
常用属性:

  1. tags: 分组标签
  2. value: 如果tags没有定义,value将作为tags使用
  3. description: API的详细描述

个人建议的写法:

1@Api(tags = "AccountController",description = "账户信息相关接口")
2public class AccountController {
3    //... ...
4}

3.2 @ApiOperation

用在方法上。对该方法的描述信息

常用属性:

  1. value: 对方法的简单描述,长度为120个字母,60个汉字。
  2. notes: 对操作的详细说明。
  3. httpMethod: 请求方式,可选值有”GET”, “HEAD”, “POST”, “PUT”, “DELETE”, “OPTIONS” and “PATCH”。
  4. code http 状态码,默认为200

个人建议的写法:

1@ApiOperation(value = "获取账号信息",
2        notes = "根据传入的参数 name 查询账号信息。",
3        httpMethod= "GET")
4@GetMapping("/get/{name}")
5public AccountInfo getAccountByName(@PathVariable String name){
6    //... ...
7}

3.3 @ApiImplicitParams 与 @ApiImplicitParam

用在方法上。对参数列表的说明,这两个注解时连用的。ApiImplicitParams 内部有多个 ApiImplicitParam,每个 ApiImplicitParam 对应一个参数,常用属性:

  1. name: 参数名称
  2. value: 参数描述
  3. paramType: 参数的传入(请求)类型,可选的值有path, query, body, header or form
  4. dataType: 参数类型。可以为类名,也可以为基本类型(String,int、boolean等)
  5. required: 是否是必填字段。

个人建议的写法:

1    @ApiImplicitParams({
2            @ApiImplicitParam(
3                    name = "name",
4                    value = "用户名",
5                    paramType = "path",
6                    dataType = "String",
7                    required = true
8            )
9    })
10    @GetMapping("/get/{name}")
11    public AccountInfo getAccountByName(@PathVariable String name){
12        //... ...
13    }

3.4 @ApiResponses 与 ApiResponse

用在方法上,对方法的返回值(响应结果)进行说明。ApiResponses内部有多个ApiResponse。
ApiResponse 常用属性:

  1. code:http状态码
  2. message:对应状态码的描述
  3. response:返回值。如果是类名的话,需要类的全路径
  4. responseContainer:如果返回类型为容器类型,可以设置相应的值。有效值为 “List”, “Set” or “Map”

个人建议的写法:

1    @ApiResponses({
2            @ApiResponse(
3                    code = 200,
4                    message = "成功",
5                    response = com.zdran.springboot.dao.AccountInfo.class
6            ),
7            @ApiResponse(
8                    code = 404,
9                    message = "网络异常",
10                    response = Exception.class
11            )
12    })
13    @GetMapping("/get/{name}")
14    public AccountInfo getAccountByName(@PathVariable String name){
15        //... ...
16    }

一般 404 的 response 值应该是自定义的异常返回对象。

3.4 @ApiModel 与 @ApiModelProperty

这两个注解是用在实体类上面的,对实体类和参数进行说明。

ApiModel: 用在类上面,对类进行说明,有两个属性

  1. value: 类的别名,默认是类名
  2. description: 类的详细描述

ApiModelProperty: 用在类的属性上,对属性进行说明。 常用属性:

  1. value: 属性的描述
  2. example: 属性的示例值

个人建议的写法:

1@ApiModel(
2        value = "AccountInfo",
3        description = "用户信息实体类"
4)
5public class AccountInfo {
6
7    @ApiModelProperty(
8            value = "账户id",
9            example = "123455",
10            dataType = "Integer"
11    )
12    private Integer accountId;
13
14    @ApiModelProperty(
15            value = "用户名",
16            example = "zdran",
17            dataType = "String"
18    )
19    private String name;

配置这些基本上就可以了,再多的话,代码入侵就有点多了。

转载请注明出处
本文链接:zdran.com/20180730.ht…