Springdoc OpenAPI 2.x 使用与配置指南(适用于 Spring Boot 3+)

Springdoc OpenAPI 2.x 使用与配置指南(适用于 Spring Boot 3+)

📦 依赖引入

<dependency>
  <groupId>org.springdoc</groupId>
  <artifactId>springdoc-openapi-starter-webmvc-ui</artifactId>
  <version>2.8.8</version> <!-- 使用最新2.x版本 -->
</dependency>

🌐 默认访问地址

  • OpenAPI 文档:http://localhost:8080/v3/api-docs
  • Swagger UI 页面:http://localhost:8080/swagger-ui.html

默认没有任何配置,Swagger UI 页面是这样的,如下:

创建SpringBoot项目,Springboot选择的版本是3.4.6,JDK选择的版本是21

在pom.xml文件中添加依赖

<dependency>
  <groupId>org.springdoc</groupId>
  <artifactId>springdoc-openapi-starter-webmvc-ui</artifactId>
  <version>2.8.8</version> <!-- 使用最新2.x版本 -->
</dependency>

⚙️ application.yml 配置示例

springdoc:
  api-docs:
    enabled: true                # 启用或禁用 OpenAPI 文档生成
    path: /v3/api-docs           # 文档的路径,默认是 /v3/api-docs
  swagger-ui:
    enabled: true                # 启用 Swagger UI 页面
    path: /swagger-ui.html       # UI 访问路径(默认)
    title: 接口文档系统
    display-request-duration: true       # 显示请求耗时
    doc-expansion: none                  # none | list | full
    operations-sorter: alpha             # 排序方式:method(按照HTTP方法排序)、alpha(按照字符排序)
    tags-sorter: alpha                   # 标签排序
    default-model-expand-depth: 2        # 控制左侧 Models(底部模型结构)面板默认展开的层级
    default-models-expand-depth: 1		 # 控制接口每个请求/响应体中模型字段的默认展开层级
    try-it-out-enabled: true             # 是否启用 Try it out 按钮
  group-configs:                         # 分组配置(适合多模块项目)
    - group: 用户模块              # 命名模块
      paths-to-match: /user/**   # 指定哪些 URL 路径下的接口会被包含进这个分组。
      packages-to-scan: com.example.controller.user # 指定扫描哪个包下的 Controller 类,用于生成接口文档。
    - group: 系统模块
      paths-to-match: /sys/**
      packages-to-scan: com.example.controller.sys

🔐 与 SpringMVC 配合放行文档接口

默认如果我们没有手动配置静态资源映射或拦截器,Swagger 页面通常也能正常访问,这是因为 Spring Boot 已经为你做了很多“默认配置”。

1. 自动配置静态资源映射

Spring Boot 自动将以下路径作为静态资源路径:

  • classpath:/META-INF/resources/
  • classpath:/resources/
  • classpath:/static/
  • classpath:/public/

而 Swagger UI 所依赖的资源(HTML、JS、CSS)恰好都在 META-INF/resources/webjars 中,因此不需要手动配置即可访问:

  • /swagger-ui.html
  • /swagger-ui/**
  • /webjars/**

2. Spring Boot 没有默认拦截所有请求

如果你没有配置任何自定义的 HandlerInterceptorFilter,那么 Spring Boot 不会拦截 /swagger-ui.html/v3/api-docs 等路径,也不会阻止静态资源加载。

springdoc-openapi 的默认路径

使用 springdoc-openapi(特别是 2.x 对应 Spring Boot 3),默认暴露以下接口:

  • Swagger UI 页面:/swagger-ui.html
  • 接口文档数据:/v3/api-docs
  • 静态资源路径:/swagger-ui/**/webjars/**

这些路径默认对外开放,无需你干预。

📌如果MVC配置是实现WebMvcConfigurer接口,无需处理;如果是继承WebMvcConfigurationSupport的mvc配置基类会导致swagger页面无法访问,目前我试过在配置中配置静态资源映射但是没有作用。配置详情


🔐 与 Spring Security 配合放行文档接口(可选)

@Configuration
public class SecurityConfig {

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

🧾 OpenAPI 信息注解配置(可选)

// 1、第一种直接加在启动类上
@OpenAPIDefinition(
    info = @Info(
        title = "示例接口文档",
        version = "1.0",
        description = "这是一个接口文档示例",
        contact = @Contact(name = "张三", email = "zhangsan@example.com")
    )
)
@SpringBootApplication
public class Application {}

// 2、第二种使用配置类
# 在config包下添加一个SpringDocConfig配置类
    
@Configuration
public class SpringDocConfig {
 
    @Bean
    public OpenAPI openAPI() {
        return new OpenAPI()
                // 配置接口文档基本信息
                .info(this.getApiInfo());
    }
 
    private Info getApiInfo() {
        return new Info()
                 // 配置文档标题
                .title("SpringBoot3集成Swagger3")
                // 配置文档描述
                .description("SpringBoot3集成Swagger3示例文档")
                // 概述信息
                .summary("SpringBoot3集成Swagger3示例文档-----描述信息")
                // 配置版本号
                .version("2.0")
                .contact(new Contact()
                        .name("张三")
                        .email("123456789@qq.com"));
    }
}

🧪 示例接口注解

@RestController
@RequestMapping("/api/user")
@Tag(name = "用户接口", description = "用户相关操作")
public class UserController {

    @Operation(summary = "根据ID获取用户信息")
    @GetMapping("/{id}")
    public User getUser(@PathVariable Long id) {
        return new User(id, "Tom");
    }
}

Swagger 3 注解使用(基于 Springdoc + OpenAPI 3)

Swagger 3 注解大多位于 io.swagger.v3.oas.annotations 包下,下面是常用注解及其使用场景分类:


✅ 控制器类级别注解

@Tag

  • 作用:对控制器进行归类和说明
  • 用法
@Tag(name = "用户模块", description = "用户管理相关接口")

✅ 方法级别注解

@Operation

  • 作用:描述一个 API 操作
  • 常用属性
    • summary:简要描述
    • description:详细描述
    • tags:所属模块
@Operation(summary = "查询用户", description = "通过ID查询用户详情")

@ApiResponses / @ApiResponse

  • 作用:定义多个或单个响应状态码及描述
@ApiResponses({
  @ApiResponse(responseCode = "200", description = "成功"),
  @ApiResponse(responseCode = "404", description = "用户不存在")
})

@RequestBody

  • 作用:描述请求体(与 Spring 自带的 @RequestBody 搭配)
@io.swagger.v3.oas.annotations.parameters.RequestBody(
  description = "用户信息请求体",
  required = true
)

✅ 参数注解

@Parameter

  • 作用:对单个参数进行说明(请求参数、路径参数等)
  • 用法
@Parameter(name = "id", description = "用户ID", example = "1")

✅ 实体类和字段注解

@Schema

  • 作用:对模型类或属性进行描述
  • 用法
@Schema(name = "User", description = "用户实体")
public class User {

    @Schema(description = "用户ID", example = "1")
    private Long id;

    @Schema(description = "用户名", example = "zhangsan")
    private String name;
}

✅ 其他常用注解

@Hidden

  • 作用:隐藏某个接口或属性,不显示在 Swagger 文档中
@Hidden
public String internalMethod() {}

🔧 实用技巧

  • @Parameter(hidden = true) 可用于隐藏参数(如登录信息)
  • @Schema(hidden = true) 隐藏某个字段
  • 可使用 @Schema(implementation = Xxx.class) 在响应中引用模型类

📌 建议

  • 实体类和接口尽量使用 @Schema@Operation 搭配,增强文档可读性
  • 避免过度注解干扰业务逻辑,可集中在文档层维护注解
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值