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

普通Spring项目配置Swagger后无法正常访问的问题求助

问题根源

配置出错的核心原因是SpringFox的核心依赖和UI依赖版本不匹配,3.x版本的springfox-swagger2不能和2.x版本的springfox-swagger-ui混用。

修复步骤

步骤1:统一依赖版本

两种方案二选一即可:

方案A:统一使用2.9.2版本(兼容性更稳定,适合老Spring项目)

把Maven依赖替换为以下内容:

<!-- for swagger -->
<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>
<!-- end of swagger dependency -->

方案B:使用3.x版本统一starter依赖

如果要使用3.0.0版本,不需要单独引入两个依赖,直接用官方提供的starter即可:

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

注意使用3.x版本时,SwaggerUI的访问地址从原来的swagger-ui.html调整为swagger-ui/index.html,同时配置类的注解需要用@EnableSwagger2WebMvc替换原来的@EnableSwagger2。

步骤2:优化配置类

现有两个配置类都加了@EnableWebMvc注解,重复添加会覆盖SpringMVC的默认配置,建议把两个配置类合并。如果使用2.9.2版本,合并后的配置如下:

package com.luv2code.springdemo.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
import springfox.documentation.builders.PathSelectors;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2;

@Configuration
@EnableSwagger2
@EnableWebMvc
public class SpringFoxConfig implements WebMvcConfigurer {                                    
    @Bean
    public Docket api() { 
        return new Docket(DocumentationType.SWAGGER_2)  
          .select()                                  
          .apis(RequestHandlerSelectors.any())              
          .paths(PathSelectors.any())                          
          .build();                                           
    }

    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        registry.addResourceHandler("swagger-ui.html")
          .addResourceLocations("classpath:/META-INF/resources/");
        registry.addResourceHandler("/webjars/**")
          .addResourceLocations("classpath:/META-INF/resources/webjars/");
    }
}

另外WebMvcConfigurerAdapter在Spring 5以后已经被标记为废弃,直接实现WebMvcConfigurer接口即可。

步骤3:验证访问

修改完成后重启项目,访问对应版本的SwaggerUI地址即可正常查看接口文档。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.05 07:57:04