You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Spring Boot集成Swagger2启动报空指针异常如何解决

问题原因

该报错为Spring Boot 2.6+ 版本与 Swagger2 2.9.x 版本不兼容导致的:Spring Boot 2.6 开始将默认的 MVC 路径匹配策略从AntPathMatcher改为PathPatternParser,而 Swagger2 2.9.x 版本的底层路径解析逻辑仍依赖旧的AntPathMatcher,路径解析时返回空值触发空指针异常。

解决方案

方案1:修改全局路径匹配策略(适配现有Swagger2.9.2版本,改动最小)

在项目的application.properties配置文件中添加以下配置,将路径匹配策略改回旧版本的实现:

spring.mvc.pathmatch.matching-strategy=ant_path_matcher

如果用的是application.yml,配置如下:

spring:
  mvc:
    pathmatch:
      matching-strategy: ant_path_matcher

注意:如果项目中添加了@EnableWebMvc注解,该自动配置不会生效,需要手动配置WebMvc的路径匹配策略为AntPathMatcher。

方案2:升级Springfox到3.0.0版本

如果不想修改全局路径匹配规则,可以将Swagger相关依赖替换为3.0.0版本的整合starter:

  • 首先删除原有pom.xml中所有io.springfox相关的旧依赖
  • 引入新的starter依赖:
<dependency>
    <groupId>io.springfox</groupId>
    <artifactId>springfox-boot-starter</artifactId>
    <version>3.0.0</version>
</dependency>
  • 将启动类上的@EnableSwagger2注解替换为@EnableOpenApi

方案3:替换为维护中的SpringDoc OpenAPI(更推荐)

Springfox已经停止维护,长期来看更推荐迁移到SpringDoc OpenAPI,替换步骤如下:

  • 删除所有原有Swagger/Springfox相关依赖
  • 引入对应Spring Boot版本的SpringDoc依赖:
    • Spring Boot 2.x 版本引入:
    <dependency>
        <groupId>org.springdoc</groupId>
        <artifactId>springdoc-openapi-ui</artifactId>
        <version>1.6.15</version>
    </dependency>
    
    • Spring Boot 3.x 版本引入:
    <dependency>
        <groupId>org.springdoc</groupId>
        <artifactId>springdoc-openapi-starter-webmvc-ui</artifactId>
        <version>2.2.0</version>
    </dependency>
    
  • 移除启动类上的@EnableSwagger2注解即可直接使用,默认文档地址为http://localhost:8080/swagger-ui.html

内容的提问来源于stack exchange,提问作者Shubham Rai

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.25 20:24:03