SpringBoot:整合 Swagger / SpringDoc OpenAPI3 完整版步骤教程 / API 文档自动生成工具

发布时间:2026/7/23 4:46:38
SpringBoot:整合 Swagger / SpringDoc OpenAPI3 完整版步骤教程 / API 文档自动生成工具 说明1、SpringFox旧 Swagger2大量存在兼容 bugSpringBoot2.6、3.x 报错本文使用SpringDoc OpenAPI 3页面就是 Swagger UI2、SpringBoot2.x/ SpringBoot3.x 区分依赖版本下文标注清楚3、全程一步一步操作复制即可运行前置说明访问地址最终http://localhost:你的端口/swagger-ui/index.html第 1 步引入 Maven 依赖 pom.xml情况 ASpringBoot 3.xJDK17!-- SpringDoc OpenAPI3 Swagger -- dependency groupIdorg.springdoc/groupId artifactIdspringdoc-openapi-starter-webmvc-ui/artifactId version2.5.0/version /dependency情况 BSpringBoot 2.xJDK8 / JDK11dependency groupIdorg.springdoc/groupId artifactIdspringdoc-openapi-ui/artifactId version1.7.0/version /dependency引入依赖后刷新 Maven等待依赖下载完成。第 2 步创建 Swagger 配置类可选用于修改文档标题、描述新建配置类SwaggerOpenApiConfig.java放在你的 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 / 实体类示例返回对象展示注释DTOData Transfer Object数据传输对象和实体类Entity是后端开发中常用的两种数据模型类它们都可以通过 Swagger/OpenAPI 注解来展示字段说明。在 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 zhangsanexample.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 端口。如果打不开页面往下看【常见问题排查】成功了第 5 步可选SpringSecurity / 拦截器放行 swagger 资源如果项目使用 SpringSecurity、自定义拦截器会拦截 swagger 地址页面无法加载需要放行地址 放行路径清单/v3/api-docs/** /swagger-ui/** /swagger-ui/index.htmlSpringSecurity 放行示例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.enabletrue 才开启 ConditionalOnProperty(name springdoc.enable, havingValue true) public class SwaggerOpenApiConfig { // ...代码不变 }application.ymlspringdoc: enable: true # dev开启prod改为false 高频踩坑排查清单重点问题 1打开页面但是一片空白看不到自己写的接口Controller 必须加RestController接口方法必须是public启动项目后不要直接访问静态 html先让 Spring 加载所有 Controller检查请求路径是否有统一前缀server.servlet.context-path访问地址要带上前缀问题 2404 找不到页面核对地址✅ 正确/swagger-ui/index.html❌ 旧 swagger2 地址/swagger-ui.html在 SpringDoc 中失效问题 3实体类返回值不显示注释确认导入注解包import io.swagger.v3.oas.annotations.media.Schema;不要导错旧 swagger2 的ApiModel问题 4SpringBoot3 启动报错必须使用springdoc-openapi-starter-webmvc-ui不能使用 2.x 旧依赖补充如果你执意使用老版本 Swagger2SpringFox不推荐pom 依赖dependency groupIdio.springfox/groupId artifactIdspringfox-swagger2/artifactId version2.9.2/version /dependency dependency groupIdio.springfox/groupId artifactIdspringfox-swagger-ui/artifactId version2.9.2/version /dependency配置类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 依赖包内部

相关新闻

最新新闻

日新闻

周新闻

月新闻