Spring Boot整合集成Swagger3.x

332 阅读2分钟

这两天学了一下Swagger,在SpringBoot整合Swagger的时候遇到点问题,在网上搜集了很多资料以后,发现Swagger3.x和Swagger2.x用法的一些区别。

如果使用不正确,在访问swagger-ui.html会出现404的问题

以整合Swagger为主,按照步骤,同时说明与Swagger2.x的一些区别

1、导入依赖坐标(不需用都导入,选择自己需要的版本)

<!-- Swagger3.x 核心依赖 -->
<dependency>
    <groupId>io.springfox</groupId>
    <artifactId>springfox-boot-starter</artifactId>
    <version>3.0.0</version>
</dependency>
<!-- Swagger2.x 核心依赖 -->
<dependency>
    <groupId>io.springfox</groupId>
    <artifactId>springfox-swagger-ui</artifactId>
    <version>2.9.2</version>
</dependency>
<dependency>
    <groupId>io.springfox</groupId>
    <artifactId>springfox-swagger2</artifactId>
    <version>2.9.2</version>
</dependency>

2、yml配置

Spring Boot 2.6.x版本中引入的一个新的路径匹配策略path_pattern_parser,但是SpringFox 3.0.0中默认期望使用ant_path_matcher作为路径匹配策略,因此存在的兼容性问题。如果直接引入SpringFox 3.0.0,可能会出现启动失败的问题。

所以需要在application.yml中添加下面的配置显式地告诉Spring MVC使用ant_path_matcher作为路径匹配策略。

spring:
  mvc:
    pathmatch:
      matching-strategy: ant_path_matcher

下面的配置用来启用Swagger UI的,这是Swagger的Web界面,允许用户查看和测试API。如果使用的是Spring Boot 2.6.x或更高版本,并希望整合Swagger 3.0.0,需要确保在application.properties或application.yml中添加上述配置。这样可以避免启动时的异常,并确保Swagger UI能够正常工作。

springfox:
  documentation:
    swagger-ui:
      enabled: true

以上配置在Swagger2.x中就不需要添加

3、配置类

在Swagger3.x使用的是@EnableOpenApi作为启动类配置注解

在Swagger2.x使用的是@EnableSwagger2作为启动类配置注解

@Configuration
@EnableOpenApi
//@EnableSwagger2
    public class SwaggerConfig {}

4、运行项目并访问Swagger页面

在Swagger2.x中的访问路径是http://127.0.0.1:8080/swagger-ui.html​编辑

在Swagger3.x中的访问路径是http://127.0.0.1:8080/swagger-ui/index.html​编辑

算是个入门练习吧!!!