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

Spring Boot集成Swagger遇404:Swagger UI无法正常访问

问题分析与解决方案

你的配置存在以下几个关键问题,导致Swagger UI无法正常工作:

1. 依赖冗余问题

springfox-boot-starter:3.0.0已经内置了springfox-swagger-ui的依赖,无需单独重复引入,直接删除pom.xml中的第二个依赖:

<!-- 移除该重复依赖 -->
<dependency>
    <groupId>io.springfox</groupId>
    <artifactId>springfox-swagger-ui</artifactId>
    <version>3.0.0</version>
</dependency>

2. 注解与文档类型不匹配

  • Springfox 3.x版本不需要在主类添加@EnableSwagger2注解,直接删除该注解即可(starter会自动完成OpenAPI的基础配置)。
  • 你的Docket使用了DocumentationType.SWAGGER_2,但Springfox 3.x默认生成OpenAPI 3.0格式的文档(对应/v3/api-docs),两者不匹配会导致UI无法识别文档地址。修改SwaggerConfig类:
@Configuration
public class SwaggerConfig {
    @Bean
    public Docket api() {
        // 替换为OpenAPI 3.0对应的文档类型
        return new Docket(DocumentationType.OAS_30)
                .select()
                .apis(RequestHandlerSelectors.any())
                .paths(PathSelectors.any())
                .build();
    }
}

3. Spring Boot 2.4+路径匹配策略冲突

Spring Boot 2.4及以上版本默认使用path-pattern-matcher作为路径匹配策略,但Springfox 3.x暂不兼容该策略,需在application.properties或application.yml中添加配置:

spring.mvc.pathmatch.matching-strategy=ant-path-matcher

4. 安全配置优化(可选)

你当前的安全配置存在重复的authorizeRequests和csrf()配置,可合并为更简洁的写法:

@Override
protected void configure(HttpSecurity http) throws Exception {
    http.cors()
        .and()
        .csrf().disable()
        .authorizeRequests()
            .antMatchers("/temp", "/webjars/**", "/swagger-ui/**", "/v3/api-docs/**", "/swagger-resources/**")
            .permitAll()
            .anyRequest().authenticated()
        .and()
        .httpBasic();

    http.addFilterAfter(jwtRequestFilter, UsernamePasswordAuthenticationFilter.class);
}

完成以上修改后重启应用,访问http://localhost:8080/swagger-ui/index.html即可正常加载Swagger UI,它会自动读取/v3/api-docs的文档数据。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.23 04:50:06