商城首页欢迎来到中国正版软件门户

您的位置: 首页 > 文章列表 > 编程开发 > SpringBoot集成SpringDocOpenAPI(替代SpringFox/Swagger2)的完整步骤

SpringBoot集成SpringDocOpenAPI(替代SpringFox/Swagger2)的完整步骤

  发布于2026-07-23 阅读(0)

扫一扫,手机访问

一、先说明几个核心点,免得走弯路 SpringFox(也就是老版 Swagger2)在 SpringBoot 2.6+ 和 3.x 上兼容性确实一言难尽,各种报错。所以这篇直接用 **SpringDoc OpenAPI 3**,页面依然是熟悉的 Swagger UI 风格。 SpringBoot2.x 和 3.x 的依赖版本不一样,下面会标注清楚。 全程步骤式操作,复制就能跑起来。

前置说明

最终访问地址:http://localhost:你的端口/swagger-ui/index.html

第 1 步:引入 Ma ven 依赖 pom.xml

情况 A:SpringBoot 3.x(JDK17+)



    org.springdoc
    springdoc-openapi-starter-webmvc-ui
    2.5.0

情况 B:SpringBoot 2.x(JDK8 / JDK11)


    org.springdoc
    springdoc-openapi-ui
    1.7.0

引入后刷新 Ma ven,等依赖下载完即可。

第 2 步:创建 Swagger 配置类(可选,用于修改文档标题、描述)

新建 SwaggerOpenApiConfig.ja va,放在 config 包下:

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 SwaggerOpenApiConfig {
    @Bean
    public OpenAPI openAPI() {
        return new OpenAPI()
                .info(new Info()
                        .title("项目后端接口文档")     //文档标题
                        .version("V1.0")               //版本
                        .description("所有业务接口在线调试文档")); //描述
    }
}

不写这个配置类也能正常打开 Swagger,只是顶部没有自定义标题。

第 3 步【核心】给你的 Controller 接口添加注解(让接口显示在文档)

OpenAPI3 常用注解对照表

注解

作用

@Tag(name = "模块名称")

加在 Controller 类上,划分接口模块

@Operation(summary = "接口名称",description = "详细描述")

标记单个接口

@Parameter(description = "参数说明")

url 传参说明

@Schema(description = "字段注释")

实体类、DTO 字段注释

其实不加注解也能用。SpringDoc 会自动扫描所有 @RestController,直接生成文档。

Controller 完整示例

import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("/user")
@Tag(name = "用户管理模块")
public class UserController {
    @GetMapping("/get")
    @Operation(summary = "根据ID获取用户信息", description = "传入用户id,查询基础用户数据")
    public String getUser(Long userId){
        return "用户信息";
    }
}

DTO / 实体类示例(返回对象展示注释)

在 Swagger 文档中,当接口返回或接收对象时,字段上的 @Schema 注解能让文档清晰地展示每个字段的含义和示例值。

import io.swagger.v3.oas.annotations.media.Schema;
import lombok.Data;

@Data
@Schema(description = "用户返回实体")
public class UserDTO {
    @Schema(description = "用户唯一ID", example = "1001")
    private Long userId;

    @Schema(description = "用户姓名", example = "张三")
    private String userName;

    @Schema(description = "用户邮箱", example = "zhangsan@example.com")
    private String email;

    @Schema(description = "创建时间", example = "2023-10-01 12:00:00")
    private String createTime;
}

关键点:

@Schema(description = "..."):用于描述整个类或单个字段的作用。

@Schema(example = "..."):提供字段的示例值,方便在 Swagger UI 中直接测试。

实体类(如 JPA Entity)的注解用法完全相同,但通常用于数据库映射。

确保导入正确的包:import io.swagger.v3.oas.annotations.media.Schema;,不要用旧版 Swagger2 的 @ApiModel

这样配置后,Swagger 文档中该对象的字段就会显示清晰的注释和示例,可读性大幅提升。

第 4 步:启动项目,访问文档地址

http://localhost:8080/swagger-ui/index.html

把 8080 替换成你项目的 server.port 端口。

如果打不开页面:往下看【常见问题排查】

成功了

SpringBoot集成SpringDocOpenAPI(替代SpringFox/Swagger2)的完整步骤

第 5 步(可选):SpringSecurity / 拦截器放行 swagger 资源

如果项目使用 SpringSecurity、自定义拦截器,会拦截 swagger 地址,页面无法加载,需要放行地址:

/v3/api-docs/**
/swagger-ui/**
/swagger-ui/index.html

SpringSecurity 放行示例

@Override
public void configure(HttpSecurity http) throws Exception {
    http.authorizeHttpRequests()
            .requestMatchers("/v3/api-docs/**","/swagger-ui/**").permitAll()
            .anyRequest().authenticated();
}

自定义 WebMvc 拦截器放行

@Override
public void addInterceptors(InterceptorRegistry registry) {
    registry.addInterceptor(loginInterceptor)
            .addPathPatterns("/**")
            .excludePathPatterns("/v3/api-docs/**","/swagger-ui/**");
}

第 6 步(可选)区分环境:只开发环境开启 Swagger

一般生产环境关闭接口文档,用 @ConditionalOnProperty 修改配置类:

@Configuration
// yml配置 springdoc.enable=true 才开启
@ConditionalOnProperty(name = "springdoc.enable", ha vingValue = "true")
public class SwaggerOpenApiConfig {
    // ...代码不变
}

application.yml

springdoc:
  enable: true # dev开启;prod改为false

高频踩坑排查清单(重点!)

问题 1:打开页面,但是一片空白,看不到自己写的接口

  1. Controller 必须加 @RestController
  2. 接口方法必须是 public
  3. 启动项目后不要直接访问静态 html,先让 Spring 加载所有 Controller
  4. 检查请求路径是否有统一前缀 server.servlet.context-path,访问地址要带上前缀

问题 2:404 找不到页面

核对地址!

✅ 正确:/swagger-ui/index.html

❌ 旧 swagger2 地址 /swagger-ui.html 在 SpringDoc 中失效

问题 3:实体类返回值不显示注释

确认导入注解包:

import io.swagger.v3.oas.annotations.media.Schema;

不要导错旧 swagger2 的@ApiModel

问题 4:SpringBoot3 启动报错

必须使用 springdoc-openapi-starter-webmvc-ui,不能使用 2.x 旧依赖

补充:如果你执意使用老版本 Swagger2(SpringFox,不推荐)

pom 依赖


    io.springfox
    springfox-swagger2
    2.9.2


    io.springfox
    springfox-swagger-ui
    2.9.2

配置类

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 Swagger2Config {
    @Bean
    public Docket docket(){
        return new Docket(DocumentationType.SWAGGER_2)
                .select()
                // 重点!修改为你的controller包路径
                .apis(RequestHandlerSelectors.basePackage("com.xxx.controller"))
                .build();
    }
}

访问地址:http://localhost:8080/swagger-ui.html

SpringBoot 2.6 以上必须额外配置 yml 解决路径匹配报错

spring:
  mvc:
    pathmatch:
      matching-strategy: ant_path_matcher

问题5、本地有Swagger UI文件吗

你在项目目录里找不到任何 swagger-ui 的 HTML/CSS/JS 文件。

Swagger UI 的静态文件打包在 JAR 依赖包内部

SpringBoot集成SpringDocOpenAPI(替代SpringFox/Swagger2)的完整步骤

SpringBoot集成SpringDocOpenAPI(替代SpringFox/Swagger2)的完整步骤

SpringBoot集成SpringDocOpenAPI(替代SpringFox/Swagger2)的完整步骤

本文转载于:https://www.jb51.net/program/367910svw.htm 如有侵犯,请联系zhengruancom@outlook.com删除。
免责声明:正软商城发布此文仅为传递信息,不代表正软商城认同其观点或证实其描述。

热门关注