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

Spring 5.3非Boot项目集成springdoc-openapi-ui报404错误求助

解决Spring 5.3(非Spring Boot)集成springdoc-openapi-ui后Swagger页面404问题

1. 补充非Spring Boot环境所需依赖

springdoc-openapi-ui在纯Spring MVC环境下需要额外核心依赖支持,确保pom.xml中包含:

<dependency>
    <groupId>org.springdoc</groupId>
    <artifactId>springdoc-openapi-webmvc-core</artifactId>
    <version>1.8.0</version>
</dependency>
<dependency>
    <groupId>org.springdoc</groupId>
    <artifactId>springdoc-openapi-ui</artifactId>
    <version>1.8.0</version>
</dependency>

2. 手动配置Swagger UI静态资源映射

纯Spring MVC不会自动注册Swagger UI的静态资源,需实现WebMvcConfigurer添加资源映射:

@Configuration
public class WebMvcConfig implements WebMvcConfigurer {
    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        // 映射swagger-ui静态资源(版本需与springdoc-openapi-ui内置webjar版本匹配)
        registry.addResourceHandler("/swagger-ui/**")
                .addResourceLocations("classpath:/META-INF/resources/webjars/swagger-ui/4.18.3/");
        // 映射API文档接口
        registry.addResourceHandler("/v3/api-docs/**")
                .addResourceLocations("classpath:/META-INF/resources/");
    }
}

注:1.8.0版本的springdoc-openapi-ui内置swagger-ui 4.18.3,可通过Maven依赖树确认具体版本。

3. 完善Spring Security放行路径

除swagger-ui.html外,需放行所有Swagger相关资源与API接口,修改Security配置:

@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.authorizeRequests()
                .antMatchers(
                    "/swagger-ui/**",
                    "/v3/api-docs/**",
                    "/swagger-resources/**",
                    "/webjars/**"
                ).permitAll()
                .anyRequest().authenticated();
    }
}

4. 检查OpenApiConfig配置正确性

确保配置类标注@Configuration并定义OpenAPI Bean:

@Configuration
public class OpenApiConfig {
    @Bean
    public OpenAPI customOpenAPI() {
        return new OpenAPI()
                .info(new Info()
                        .title("项目API文档")
                        .version("1.0")
                        .description("Spring MVC项目接口文档"));
    }
}

5. 使用正确的访问URL

非Spring Boot环境下,Swagger UI的正确访问路径为:
http://localhost:8080/swagger-ui/index.html
若项目有自定义Servlet上下文路径(如/api),需添加前缀:http://localhost:8080/api/swagger-ui/index.html

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.21 09:20:03