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

Spring Boot项目中Swagger UI无法访问问题求助

解决Swagger启动报错java.lang.TypeNotPresentException: Type javax.servlet.http.HttpServletRequest not present及UI无法访问问题

这个问题核心原因是Spring Boot版本与Swagger依赖版本不兼容,尤其是Spring Boot 3.x切换到Jakarta EE规范后,旧版Swagger2(io.springfox)依赖仍使用javax.servlet包,导致类找不到异常。以下是针对性解决方案:

1. 替换/调整Swagger依赖

针对Spring Boot 3.x

旧版Swagger2(springfox系列)已停止维护,不支持Jakarta EE,直接替换为SpringDoc(官方推荐的Swagger3实现):

  • 移除pom.xml中所有springfox相关依赖(如springfox-swagger2、springfox-swagger-ui)
  • 添加SpringDoc依赖:
<dependency>
    <groupId>org.springdoc</groupId>
    <artifactId>springdoc-openapi-starter-webmvc-ui</artifactId>
    <version>2.2.0</version> <!-- 版本需匹配Spring Boot 3.x,可根据你的Boot版本调整 -->
</dependency>

针对Spring Boot 2.x

确保springfox版本与Spring Boot兼容,比如Spring Boot 2.7.x搭配springfox 3.0.0:

<dependency>
    <groupId>io.springfox</groupId>
    <artifactId>springfox-boot-starter</artifactId>
    <version>3.0.0</version>
</dependency>

2. 修正配置类

Spring Boot 3.x(SpringDoc)

移除@EnableSwagger2注解,改用OpenAPI Bean配置:

import io.swagger.v3.oas.models.OpenAPI;
import io.swagger.v3.oas.models.info.Info;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
public class OpenApiConfig {
    @Bean
    public OpenAPI customOpenAPI() {
        return new OpenAPI()
                .info(new Info()
                        .title("你的项目API文档")
                        .version("1.0")
                        .description("API功能描述"));
    }
}

Spring Boot 2.x(springfox)

保留@EnableSwagger2,检查Docket配置是否正确扫描控制器:

import springfox.documentation.builders.PathSelectors;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
@EnableSwagger2
public class SwaggerConfig {
    @Bean
    public Docket api() {
        return new Docket(DocumentationType.SWAGGER_2)
                .select()
                .apis(RequestHandlerSelectors.basePackage("com.yourpackage.controller")) // 替换为你的控制器包路径
                .paths(PathSelectors.any())
                .build();
    }
}

3. 调整Swagger UI访问路径

  • Spring Boot 3.x(SpringDoc)的访问路径是:http://localhost:8080/swagger-ui/index.html(注意不是旧的swagger-ui.html)
  • Spring Boot 2.x(springfox)仍使用:http://localhost:8080/swagger-ui.html

4. 清理冲突依赖

检查pom.xml中是否存在javax.servlet-api依赖,Spring Boot 3.x应使用jakarta.servlet-api,如果有遗留的javax相关依赖,直接移除,Spring Boot会自动管理适配版本。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.22 22:07:01