SpringBoot-(二十六)SpringBoot集成Swagger3

本文最后更新于:September 25, 2022 pm

SpringBoot框架中有两个非常重要的策略:开箱即用和约定优于配置。其设计目的是用来简化新Spring应用的初始搭建以及开发过程。该框架使用了特定的方式来进行配置,从而使开发人员不再需要定义样板化的配置。

目录

实现SpringBoot集成Swagger3

导入依赖

1
2
3
4
5
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-boot-starter</artifactId>
<version>3.0.0</version>
</dependency>

添加配置

1
2
3
4
spring:
mvc:
pathmatch:
matching-strategy: ANT_PATH_MATCHER

关闭Swagger配置:

1
2
3
springfox:
documentation:
enabled: false

可以配合多环境使用

添加注解

在启动类上添加注解。

1
2
3
4
5
6
7
8
9
@SpringBootApplication
@EnableOpenApi
public class AdminApiApplication {

public static void main(String[] args) {
SpringApplication.run(AdminApiApplication.class, args);
}

}

访问

输入访问路径:前缀路径/swagger-ui/index.html。

  • 这里的前缀路径一般指的是配置文件中配置的路径server.servlet.context-path的值。如果没有则无需管。

自定义信息

添加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
30
31
32
33
34
35
36
37
38
package com.tothefor.adminapi.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import springfox.documentation.builders.ApiInfoBuilder;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.service.Contact;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;

/**
* @Author DragonOne
* @Date 2022/9/19 14:45
* @Title
* @Description
*/

@Configuration
public class SwaggerConfig {
@Bean
public Docket docket() {
return new Docket(DocumentationType.OAS_30)
.apiInfo(new ApiInfoBuilder()
.contact(new Contact("TTF", "https://www.baidu.com", "825***@qq.com"))
.title("Swagger3测试项目")
.description("测试描述")
.version("1.0")
.build()
)
.select()
// 设置扫描那些包里面的。也可以通过withClassAnnotation实现只扫描被指定注解的api
.apis(RequestHandlerSelectors.basePackage("com.tothefor.adminapi.T"))
.build()

;
}
}

注意URL不能写 www.baidu.com

第三方UI界面

导入依赖:

1
2
3
4
5
<dependency>
<groupId>com.github.xiaoymin</groupId>
<artifactId>swagger-bootstrap-ui</artifactId>
<version>1.9.6</version>
</dependency>

输入访问地址: 前缀路径/doc.html。前缀路径定义见前面。

使用

⚠️注意:实体类要有接口用于返回值,才会显示。

接口

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
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
package com.tothefor.adminapi.T;

import com.alibaba.csp.sentinel.annotation.SentinelResource;
import com.alibaba.fastjson.JSONObject;
import com.tothefor.adminapi.BizErrors;
import com.tothefor.adminapi.client.UserApiClient;
import com.tothefor.admincore.service.AdminService;
import com.tothefor.sdk.CustomException.BizRuntimeException;
import io.swagger.annotations.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import springfox.documentation.annotations.ApiIgnore;

import javax.annotation.Resource;


/**
* @Author DragonOne
* @Date 2022/9/13 07:38
* @Title
* @Description
*/

@Api(tags = {"管理员","后台"},description = "测试描述")
@RestController
@RequestMapping("/admin")
@RefreshScope
public class ATcontroller {


@Autowired
private AdminService adminService;

@Resource
private UserApiClient userApiClient;

@Value("${ttf.name}")
private String name;

@ApiOperation("测试接口描述")
@ApiResponses({
@ApiResponse(code = 222,message = "状态码提示信息222"),
@ApiResponse(code = 500,message = "状态码提示信息500")
})

@ApiIgnore
@SentinelResource(value = "queryAll", fallback = "quick")
@RequestMapping("/queryAll")
public Object queryAll() {
return new JSONObject()
.fluentPut("total", adminService.queryAll())
;
}

public Object quick(Throwable e) {
throw new BizRuntimeException(BizErrors.ERROR);
}

@SentinelResource("param")
@RequestMapping("/getP")
public Object getP(@ApiParam("参数描述a") @RequestParam(value = "a",required = false) Integer a,
@ApiParam("参数描述b") @RequestParam(value = "b",required = false) Integer b,
@ApiParam("参数描述c") @RequestParam(value = "c",required = false) Integer c) {
return new JSONObject()
.fluentPut("ok", "a:" + a + " b: " + b + "c:" + c)
;
}

}

  • @Api:

    • tags:用于接口类分类。
    • description:用于描述。
  • @ApiOperation:用于接口的描述。

  • @ApiResponses:用于设置返回状态码的描述。

    • @ApiResponse:设置一个状态码。
      • code:状态码
      • message:状态信息。
  • @ApiIgnore:忽略接口,不显示。

  • @ApiParam:参数描述。

实体类

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
package com.tothefor.adminapi.T.entityTest;

import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;

/**
* @Author DragonOne
* @Date 2022/9/19 15:18
* @Title
* @Description
*/
@ApiModel(description = "实体类描述")
public class TestApiEntity {

@ApiModelProperty("属性描述id")
private Long id;
@ApiModelProperty("属性描述name")
private String name;
@ApiModelProperty("属性描述age")
private Integer age;
}

  • @ApiModel:
    • description:属性用于实体类的描述。
  • @ApiModelProperty:用于实体类属性的描述。

报错问题

1
org.springframework.context.ApplicationContextException: Failed to start bean 'documentationPluginsBootstrapper'; nested exception is java.lang.NullPointerException

主要原因:这是因为Spring Boot 2.6.x 和Swagger 3.0.0 整合的时候,报的错。因为Springfox 使用的路径匹配是基于AntPathMatcher的,而Spring Boot 2.6.X使用的是PathPatternMatcher。

  • 解决方案如下:(添加配置即可)
1
2
3
4
spring:
mvc:
pathmatch:
matching-strategy: ANT_PATH_MATCHER