SpringBoot集成Swagger2 的3.0版本

一、导入依赖

<!--springfox-boot-starter  包含springfox-Swagger2-3.0 和 springfox-Swagger-ui-3.0-->
        <dependency>
            <groupId>io.springfox</groupId>
            <artifactId>springfox-boot-starter</artifactId>
            <version>3.0.0</version>
        </dependency>

二、配置SwaggerConfig使能Swagger2

@Configuration
@EnableSwagger2
public class SwaggerConfig {
}

这里仅仅是让他能使用,并没有做任何自定义配置,走的默认配置

三、在主配置文件中添加配置(Springboot2.6以下版本的话可以不用配置)

spring:
  mvc:
    pathmatch:
      matching-strategy: ant_path_matcher

四、在主启动类上添加@EnableOpenApi注解

@EnableOpenApi
@SpringBootApplication
public class SpringBoot07SwaggerApplication {

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

}

五、启动项目,访问http://localhost:8080/swagger-ui/index.html

在这里插入图片描述


解释

Springboot2.6以上版本如果不在yaml中配置,直接启动,会报错

Failed to start bean ‘documentationPluginsBootstrapper’; nested exception is java.lang.NullPointerEx

原因:Springboot2.6以后将SpringMVC 默认路径匹配策略从AntPathMatcher 更改为PathPatternParser,导致出错,
我用的是Springboot2.7.4,2.6以下版本的话可以不用配置

访问路径的变化
观察一下springfox-Swagger-ui-3.0的目录结构
在这里插入图片描述
如果还访问之前的swagger-ui.html的话,就只能404了

所以在主启动类上添加@EnableOpenApi 注解并访问http://localhost:8080/swagger-ui/index.html

但这个时候,如果添加的依赖是

<dependency>
    <groupId>io.springfox</groupId>
    <artifactId>springfox-swagger2</artifactId>
    <version>3.0.0</version>
</dependency>
<dependency>
    <groupId>io.springfox</groupId>
    <artifactId>springfox-swagger-ui</artifactId>
    <version>3.0.0</version>
</dependency>

这个注解会报错,因为没有,所以直接使用下面这个依赖就好了,他同时也包含了这两个依赖

<dependency>
    <groupId>io.springfox</groupId>
    <artifactId>springfox-boot-starter</artifactId>
    <version>3.0.0</version>
</dependency>

在这里插入图片描述

posted on 2022-10-13 10:48  霍志杰  阅读(349)  评论(0)    收藏  举报  来源

导航