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

非Spring Boot的Spring MVC集成Springfox-Swagger UI 3.0.0遇404求助

解决Spring MVC(非Spring Boot)集成Springfox Swagger UI 3.0.0的404问题

1. 优先处理Spring Security拦截规则(核心问题)

因为你用了Spring Security,所有Swagger相关路径大概率被拦截了,必须在Security配置类中添加放行规则:

@Override
protected void configure(HttpSecurity http) throws Exception {
    http.authorizeRequests()
        // 放行Swagger全量资源
        .antMatchers(
            "/swagger-ui/**",
            "/v3/api-docs/**",
            "/webjars/**"
        ).permitAll()
        // 其他接口的权限配置保留原有逻辑
        .anyRequest().authenticated();
}

注意:Swagger3.0.0的API文档路径是/v3/api-docs,不是旧版的/v2/api-docs,这是很多人踩坑的点。

2. 修正Spring MVC的XML配置

你的现有资源映射存在匹配问题,调整为以下配置:

<!-- 必须开启MVC注解驱动,否则Swagger注解无法生效 -->
<mvc:annotation-driven />

<!-- Swagger UI静态资源映射 -->
<mvc:resources mapping="/swagger-ui/**" location="classpath:/META-INF/resources/webjars/springfox-swagger-ui/"/>
<!-- API文档接口映射 -->
<mvc:resources mapping="/v3/api-docs" location="classpath:/META-INF/resources/"/>

<!-- 配置跳转规则,访问/swagger-ui直接导向index.html -->
<mvc:view-controller path="/swagger-ui" view-name="forward:/swagger-ui/index.html"/>

3. 调整Swagger配置类适配3.0规范

现有配置类可以适配,但调整后更贴合Swagger3的要求:

@EnableOpenApi // 替换@EnableSwagger2,适配OpenAPI 3.0规范
@EnableWebMvc
@Component // 确保Spring能扫描到这个配置类,或者保留XML中的bean配置二选一即可
public class SwaggerConfig {
    @Bean
    public Docket api() {
        return new Docket(DocumentationType.OAS_30) // 改为OAS_30,对应Swagger3标准
                .select()
                .apis(RequestHandlerSelectors.basePackage("com.example.controller")) // 建议指定controller包,避免扫描无关类
                .paths(PathSelectors.any())
                .build()
                .apiInfo(apiInfo());
    }

    private ApiInfo apiInfo() {
        return new ApiInfoBuilder()
                .title("Api Services")
                .description("Api Services")
                .version("v1")
                .build();
    }

    @Bean
    public UiConfiguration uiConfiguration() {
        return UiConfigurationBuilder
                .builder()
                .defaultModelsExpandDepth(-1)
                .build();
    }
}

4. 补全依赖(可选但稳妥)

在pom.xml中添加Swagger3的OAS依赖,避免潜在的缺失:

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

5. 验证访问路径

配置完成后,正确的访问地址:

  • Swagger UI:http://{host}:{port}/{context-path}/swagger-ui/index.html 或直接访问 http://{host}:{port}/{context-path}/swagger-ui
  • API文档:http://{host}:{port}/{context-path}/v3/api-docs

如果还是404,建议:

  • 检查打包后的WEB-INF/lib中是否存在springfox-swagger-ui-3.0.0.jar,确认webjar资源是否正常引入
  • 开启Spring DEBUG日志,查看资源映射的加载日志,排查路径匹配问题

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.07 19:50:31