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

Spring框架集成Springfox 3.0后无法访问Swagger文档如何解决

Springfox 3.0 无法访问Swagger UI解决方案

1. 替换启动注解

Springfox 3.0 废弃了2.x版本的@EnableSwagger2注解,需替换为@EnableOpenApi,添加在启动类或Swagger配置类上即可:

import org.springframework.context.annotation.Configuration;
import springfox.documentation.oas.annotations.EnableOpenApi;

@Configuration
@EnableOpenApi
public class SwaggerConfig {
    // 可配置Docket Bean
}

2. 高版本Spring Boot适配(Spring Boot 2.6+)

Spring Boot 2.6及以上版本默认使用PathPatternParser解析路径,和Springfox 3.0存在兼容性问题,需在application.yml或application.properties中添加如下配置:

# application.yml 配置
spring:
  mvc:
    pathmatch:
      matching-strategy: ant-path-matcher
# application.properties 配置
spring.mvc.pathmatch.matching-strategy=ant-path-matcher

3. 移除旧版本残留依赖

检查项目pom.xml,确保已完全删除2.x版本单独引入的springfox-swagger2、springfox-swagger-ui、springfox-spring-webmvc等组件,仅保留官方提供的统一starter依赖:

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

可执行mvn dependency:tree命令检查是否存在残留的冲突版本依赖,如有需手动排除。

4. 放行相关资源路径

如果项目中存在自定义拦截器、Web配置、权限框架(如Spring Security、Shiro),需将以下路径加入放行列表:

  • /swagger-ui/**:Swagger UI静态资源
  • /v3/api-docs/**:OpenAPI 3.0接口文档数据源
  • /swagger-resources/**:Swagger资源配置
  • /webjars/**:静态资源依赖

示例Spring Security放行配置:

@Configuration
public class SecurityConfig extends WebSecurityConfigurerAdapter {
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.authorizeRequests()
                .antMatchers("/swagger-ui/**", "/v3/api-docs/**", "/swagger-resources/**", "/webjars/**").permitAll()
                .anyRequest().authenticated()
                .and().csrf().disable();
    }
}

示例WebMvc拦截器放行配置:

@Configuration
public class WebConfig implements WebMvcConfigurer {
    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(customInterceptor())
                .addPathPatterns("/**")
                .excludePathPatterns("/swagger-ui/**", "/v3/api-docs/**", "/swagger-resources/**", "/webjars/**");
    }
}

5. 调整Docket配置(可选)

Springfox 3.0支持OpenAPI 3.0规范,建议将Docket的DocumentationType从原来的SWAGGER_2改为OAS_30:

@Bean
public Docket docket() {
    return new Docket(DocumentationType.OAS_30)
            .select()
            .apis(RequestHandlerSelectors.basePackage("你的业务controller所在包路径"))
            .paths(PathSelectors.any())
            .build();
}

6. 访问路径确认

如果项目配置了server.servlet.context-path,访问时需要在路径前加上上下文路径,示例:

  • 无上下文路径:http://{ip}:{port}/swagger-ui/index.html
  • 上下文路径为/demo:http://{ip}:{port}/demo/swagger-ui/index.html

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.02 16:39:03