Spring Boot集成Swagger2访问Swagger UI出现404错误求助
Spring Boot集成Swagger2 404问题解决方法
版本兼容性适配
如果你的Spring Boot版本是2.6及以上,默认路径匹配策略和springfox不兼容,需要在配置文件(application.yml/properties)中添加:spring.mvc.pathmatch.matching-strategy=ant_path_matcher要是用的Spring Boot 3.x,springfox已经不再支持,得换成springdoc-openapi相关依赖。
校验Swagger配置类
确保配置类上标注了@Configuration和对应版本的启用注解:- springfox 2.x加
@EnableSwagger2 - springfox 3.x加
@EnableOpenApi
同时检查Docket的basePackage路径是否正确,比如:
@Bean public Docket api() { return new Docket(DocumentationType.SWAGGER_2) .select() .apis(RequestHandlerSelectors.basePackage("com.your.project.controller")) // 替换成实际controller包路径 .paths(PathSelectors.any()) .build(); }- springfox 2.x加
清理冗余依赖
不要同时混合引入springfox-swagger2、springfox-swagger-ui和springfox-boot-starter:- 3.x版本只需要引入
springfox-boot-starter - 2.x版本引入
springfox-swagger2+springfox-swagger-ui即可
还要保证依赖版本和Spring Boot版本匹配,比如2.9.2对应Spring Boot 2.0-2.5,3.0.0对应Spring Boot 2.4+。
- 3.x版本只需要引入
放行Swagger相关路径
如果项目里有自定义拦截器或过滤器,必须放行以下路径:- 2.x版本:
/swagger-ui.html、/swagger-resources/**、/v2/api-docs、/webjars/** - 3.x版本:
/swagger-ui/**、/v3/api-docs/**、/swagger-resources/**、/webjars/**
示例拦截器配置:
@Override public void addInterceptors(InterceptorRegistry registry) { registry.addInterceptor(customInterceptor) .excludePathPatterns("/swagger-ui/**", "/v3/api-docs/**", "/swagger-resources/**"); }- 2.x版本:
确认访问路径正确性
- springfox 2.x默认访问地址:
http://localhost:8080/swagger-ui.html - springfox 3.x默认访问地址:
http://localhost:8080/swagger-ui/index.html或http://localhost:8080/swagger-ui/
如果项目配置了server.servlet.context-path,要加上上下文路径,比如http://localhost:8080/your-app/swagger-ui.html
- springfox 2.x默认访问地址:
内容的提问来源于stack exchange,提问作者Code-forever
相关产品推荐
相关产品推荐

