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

Spring Boot 2.7.1配置Swagger遇依赖导入问题求助

Spring Boot 2.7.1 配置Swagger无法导入类的解决办法

问题根源

Spring Boot 2.6+ 版本默认修改了路径匹配策略为PathPatternParser,而SpringFox(3.0.0及以下)仍依赖旧的AntPathMatcher,同时存在Guava版本冲突问题,这会导致依赖无法正常加载、类无法导入。

解决方案

方案1:修复SpringFox兼容性问题

  1. 修正POM依赖
    确保使用SpringFox 3.0.0版本,并排除冲突的Guava依赖(Spring Boot 2.7.x自带的Guava版本与SpringFox要求的不一致):

    <dependencies>
        <dependency>
            <groupId>io.springfox</groupId>
            <artifactId>springfox-boot-starter</artifactId>
            <version>3.0.0</version>
            <exclusions>
                <exclusion>
                    <groupId>com.google.guava</groupId>
                    <artifactId>guava</artifactId>
                </exclusion>
            </exclusions>
        </dependency>
        <!-- 引入兼容版本的Guava -->
        <dependency>
            <groupId>com.google.guava</groupId>
            <artifactId>guava</artifactId>
            <version>30.1.1-jre</version>
        </dependency>
    </dependencies>
    

    注:使用springfox-boot-starter可以自动管理相关依赖,比单独引入swagger2、swagger-ui更省心。

  2. 修改路径匹配策略
    在application.yml或application.properties中添加配置,切换回SpringFox支持的路径匹配方式:

    spring:
      mvc:
        pathmatch:
          matching-strategy: ant-path-matcher
    
  3. 刷新Maven并清理IDE缓存

    • 执行Maven的clean和compile命令
    • IDE中执行File -> Invalidate Caches...并重启,确保依赖被正确加载

方案2:替换为SpringDoc OpenAPI(推荐)

SpringFox已停止维护,SpringDoc OpenAPI是更适配Spring Boot 2.7+的替代方案:

  1. 添加SpringDoc依赖
    <dependency>
        <groupId>org.springdoc</groupId>
        <artifactId>springdoc-openapi-ui</artifactId>
        <version>1.6.14</version>
    </dependency>
    
  2. 自定义配置(可选)
    无需额外配置即可直接访问http://localhost:8080/swagger-ui/index.html查看API文档。如果需要自定义接口分组或文档信息,可添加如下配置类:
    import io.swagger.v3.oas.models.info.Info;
    import org.springdoc.core.GroupedOpenApi;
    import org.springframework.context.annotation.Bean;
    import org.springframework.context.annotation.Configuration;
    
    @Configuration
    public class OpenApiConfig {
        @Bean
        public GroupedOpenApi publicApi() {
            return GroupedOpenApi.builder()
                    .group("public")
                    .pathsToMatch("/**")
                    .build();
        }
    
        @Bean
        public Info apiInfo() {
            return new Info()
                    .title("API文档")
                    .version("1.0")
                    .description("接口描述");
        }
    }
    

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.29 11:03:17