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

Spring 5非Boot项目集成Swagger Api Docs/UI失败求助

问题排查与解决方案

这个问题我之前帮朋友排查过,核心原因是Springfox 2.7.0和Spring 5.0.5的兼容性冲突——Springfox 2.x系列是基于Spring 4.x开发的,完全没有适配Spring 5.x中RequestMappingInfoHandlerMapping这类Bean的获取逻辑,所以才会触发documentationPluginsBootStrapper的初始化异常。下面给你一步步的解决办法:

1. 升级Springfox到兼容Spring 5的版本

直接放弃Springfox 2.x,换成支持Spring 5的3.x版本(推荐3.0.0及以上)。修改你的pom.xml依赖:

<!-- 移除旧的2.7.0依赖 -->
<!-- 添加兼容Spring 5的Springfox依赖 -->
<dependency>
    <groupId>io.springfox</groupId>
    <artifactId>springfox-swagger2</artifactId>
    <version>3.0.0</version>
</dependency>
<dependency>
    <groupId>io.springfox</groupId>
    <artifactId>springfox-swagger-ui</artifactId>
    <version>3.0.0</version>
</dependency>
<!-- 非Spring Boot项目必须添加这个WebMvc适配依赖 -->
<dependency>
    <groupId>io.springfox</groupId>
    <artifactId>springfox-spring-webmvc</artifactId>
    <version>3.0.0</version>
</dependency>

2. 调整Swagger配置类的注解

Springfox 3.x针对非Spring Boot项目,需要把@EnableSwagger2替换成@EnableSwagger2WebMvc,否则无法正确启用Swagger的WebMvc支持:

@Configuration
@EnableSwagger2WebMvc // 替换原有的@EnableSwagger2
public class SwaggerConfig {
    @Bean
    public Docket api() {
        return new Docket(DocumentationType.SWAGGER_2)
                .select()
                .apis(RequestHandlerSelectors.basePackage("com.your.api.package")) // 替换成你的Controller所在包
                .paths(PathSelectors.any())
                .build()
                .apiInfo(apiInfo());
    }

    private ApiInfo apiInfo() {
        return new ApiInfoBuilder()
                .title("你的RESTful API文档")
                .description("API功能描述")
                .version("1.0")
                .build();
    }
}

3. 更新WebMvc配置类

Spring 5.x已经弃用了WebMvcConfigurerAdapter,建议直接实现WebMvcConfigurer接口,同时修正Swagger UI的静态资源映射路径(Springfox 3.x的UI资源路径有变化):

@Configuration
@EnableWebMvc
public class AppConfig implements WebMvcConfigurer { // 替换继承WebMvcConfigurerAdapter为实现WebMvcConfigurer

    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        // 配置Swagger UI的静态资源访问路径
        registry.addResourceHandler("/swagger-ui/**")
                .addResourceLocations("classpath:/META-INF/resources/webjars/springfox-swagger-ui/");
    }
}

4. 调整访问路径

完成上述配置后,访问路径需要做一点修改:

  • API文档接口:http://localhost:port/context-root/v2/api-docs(依然可用,若要v3文档则访问/v3/api-docs)
  • Swagger UI页面:http://localhost:port/context-root/swagger-ui/index.html(注意3.x不再是swagger-ui.html)

最后提醒:之前尝试的@EnableAspectJAutoProxy和这个问题无关,不用再纠结这个配置啦。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.27 07:28:19