Spring集成Swagger遇/swagger-resources/configuration/ui 404及UI空白问题
旧Spring项目Swagger集成问题解决方案
一、解决2.x版本(2.4.0/2.5.0)Swagger UI空白+404问题
1. 补全静态资源映射配置
旧Spring MVC项目需手动配置Swagger UI静态资源映射,确保相关文件能被正确访问。在WebAppConfig类中添加以下代码:
@Configuration public class WebAppConfig extends WebMvcConfigurerAdapter { @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/"); } }
如果是Spring 5及以上版本,替换继承类为WebMvcConfigurationSupport或直接实现WebMvcConfigurer(WebMvcConfigurerAdapter已过时)。
2. 校验Swagger配置类有效性
检查SpringFoxConfig的注解和扫描范围,确保覆盖你的控制器包:
@Configuration @EnableSwagger2 public class SpringFoxConfig { @Bean public Docket api() { return new Docket(DocumentationType.SWAGGER_2) .select() .apis(RequestHandlerSelectors.basePackage("com.your.package.controller")) // 替换为实际控制器包路径 .paths(PathSelectors.any()) .build() .apiInfo(apiInfo()); } private ApiInfo apiInfo() { return new ApiInfoBuilder() .title("API文档") .description("接口功能描述") .version("1.0") .build(); } }
注意:如果项目存在多Spring上下文,需确保@EnableSwagger2所在配置类被正确扫描加载。
3. 放行拦截器/过滤器中的Swagger路径
若项目有自定义拦截器或过滤器,需放行以下Swagger相关路径:
/swagger-ui.html/swagger-resources/**/v2/api-docs/webjars/**
示例拦截器配置:
@Override public void addInterceptors(InterceptorRegistry registry) { registry.addInterceptor(yourCustomInterceptor) .excludePathPatterns("/swagger-ui.html", "/swagger-resources/**", "/v2/api-docs", "/webjars/**"); }
二、解决3.0.0版本启动错误(Failed to start bean 'documentationPluginsBootstrapper')
Springfox 3.0.0与旧Spring版本(尤其是Spring MVC < 5.0)兼容性有限,若要使用需按以下操作:
- 确保项目Spring版本至少为5.2.x,Spring Boot版本(若为Boot项目)至少为2.2.x。
- 旧Spring MVC项目中使用3.0.0时,需手动配置路径匹配策略,兼容旧版本的
AntPathMatcher:
@Configuration public class WebConfig implements WebMvcConfigurer { @Override public void configurePathMatch(PathMatchConfigurer configurer) { configurer.setPathMatcher(new AntPathMatcher()); } }
同时注意,3.0.0的Swagger UI访问路径变为/swagger-ui/(带末尾斜杠),需访问http://localhost:8081/swagger-ui/。
三、通用排查点
- 检查依赖完整性:2.x版本需同时引入
springfox-swagger2和springfox-swagger-ui;3.0.0仅需引入springfox-boot-starter。 - 清理项目编译目录(如
target/classes),重新编译打包,避免旧配置残留。 - 确认访问端口
8081与项目实际启动端口一致。
内容的提问来源于stack exchange,提问作者John Little
相关产品推荐
相关产品推荐

