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

Spring Boot+Maven项目如何访问Swagger Web可视化接口界面?

Spring Boot + Java 20 + Maven 配置Swagger 解决方案

1. 修正Maven依赖(核心步骤)

Java 20 搭配 Spring Boot 3.x 时,需使用适配的 springdoc-openapi 替代已停止维护的 SpringFox。在 pom.xml 中添加如下依赖:

<dependency>
    <groupId>org.springdoc</groupId>
    <artifactId>springdoc-openapi-starter-webmvc-ui</artifactId>
    <version>2.2.0</version> <!-- 适配Spring Boot 3.x与Java 17+的稳定版本 -->
</dependency>

若使用 Spring Boot 2.x,需切换为 springdoc-openapi-starter-webmvc-ui 的 1.x 系列版本。

2. 放行Swagger资源(含Spring Security时)

如果项目集成了Spring Security,必须在安全配置中放行Swagger相关路径,否则会被拦截:

@Configuration
public class SecurityConfig {
    @Bean
    public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
        http.authorizeHttpRequests(auth -> auth
                .requestMatchers("/swagger-ui/**", "/v3/api-docs/**", "/swagger-resources/**")
                .permitAll()
                .anyRequest().authenticated()
        );
        return http.build();
    }
}

3. 配置Swagger基础信息(可选)

创建配置类自定义文档元信息,提升可读性:

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

4. 确认正确访问路径

SpringDoc OpenAPI 的默认访问路径为:

  • Swagger UI 界面:http://localhost:端口号/swagger-ui/index.html
  • API 文档数据源:http://localhost:端口号/v3/api-docs
    注意:不要沿用旧版 SpringFox 的 /swagger-ui.html 路径。

5. 常见问题排查

  • 检查控制器类是否标注 @RestController/@Controller,接口方法是否添加 @GetMapping/@PostMapping 等请求注解,Swagger仅扫描带这些注解的接口。
  • 确认配置文件未禁用Swagger:
    springdoc.api-docs.enabled=true
    springdoc.swagger-ui.enabled=true
    
  • 若启用Java模块系统,需在 module-info.java 中添加依赖声明:
    requires org.springdoc.openapi.core;
    requires org.springdoc.openapi.ui;
    

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.16 01:18:10