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

SpringBoot 3.2.0集成Swagger 2.9.2失败,不降级如何修复?

解决Spring Boot 3.2.0与Swagger 2.9.2兼容问题

问题根源

SpringFox Swagger 2.9.2完全不兼容Spring Boot 3.x版本:

  • Spring Boot 3基于Jakarta EE规范,依赖jakarta.*包;而旧版SpringFox仍使用Java EE的javax.*包,类路径冲突导致无法正常加载。
  • Spring Boot 3升级了Spring MVC 6.x,API接口有重大变更,SpringFox 2.9.2的代码无法适配新的WebMvc架构。

解决方案:替换为SpringDoc OpenAPI

SpringDoc OpenAPI是目前支持Spring Boot 3的主流API文档工具,完全兼容Swagger 3.0规范,无需降级Spring Boot。

1. 更新pom.xml依赖

移除原有的SpringFox Swagger依赖,添加SpringDoc相关依赖:

<!-- 移除以下旧依赖 -->
<!--
<dependency>
    <groupId>io.springfox</groupId>
    <artifactId>springfox-swagger2</artifactId>
    <version>2.9.2</version>
</dependency>
<dependency>
    <groupId>io.springfox</groupId>
    <artifactId>springfox-swagger-ui</artifactId>
    <version>2.9.2</version>
</dependency>
-->

<!-- 添加SpringDoc OpenAPI依赖 -->
<dependency>
    <groupId>org.springdoc</groupId>
    <artifactId>springdoc-openapi-starter-webmvc-ui</artifactId>
    <version>2.2.0</version>
</dependency>

2. 修改API文档配置类

替换原有的SpringFox配置类为SpringDoc的配置:

package com.lifepill.possystem.config;

import io.swagger.v3.oas.models.OpenAPI;
import io.swagger.v3.oas.models.info.Info;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
public class OpenApiConfig {
    @Bean
    public OpenAPI customOpenAPI() {
        return new OpenAPI()
                .info(new Info()
                        .title("POS System API")
                        .version("1.0")
                        .description("POS系统的API文档"));
    }
}
  • 该配置会生成基础的API文档信息,你可以根据需求添加全局参数、安全认证等扩展配置。

3. 访问API文档

启动项目后,通过以下地址访问Swagger UI:

  • Swagger UI页面:http://localhost:8080/swagger-ui/index.html
  • OpenAPI规范JSON:http://localhost:8080/v3/api-docs

可选扩展配置

如果需要更精细的控制(比如指定扫描的控制器包、分组管理接口),可以添加如下配置:

import io.swagger.v3.oas.models.OpenAPI;
import io.swagger.v3.oas.models.info.Info;
import org.springdoc.core.models.GroupedOpenApi;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
public class OpenApiConfig {
    @Bean
    public OpenAPI customOpenAPI() {
        return new OpenAPI()
                .info(new Info()
                        .title("POS System API")
                        .version("1.0")
                        .description("POS系统的API文档"));
    }

    @Bean
    public GroupedOpenApi publicApi() {
        return GroupedOpenApi.builder()
                .group("public")
                .pathsToMatch("/**") // 匹配所有路径
                .packagesToScan("com.lifepill.possystem.controller") // 指定扫描的控制器包
                .build();
    }
}

内容的提问来源于stack exchange,提问作者Pramitha Jayasooriya

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.04 19:07:16