Swagger 使用详解

一、使用 springdoc-openapi(推荐方案) 1. 添加依赖(Maven) 说明 : springdoc-openapi-starter-webmvc-ui 会自动扫描你的 Controller 并生成 OpenAPI 3 文档,同时内置 Swagger UI。 2. (可选)自定义 OpenAPI 信息 在 Spring Boot 的配置...

一、使用 springdoc-openapi(推荐方案)

1. 添加依赖(Maven)

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
<dependencies>
  <!-- Spring Boot Web -->
  <dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-web</artifactId>
  </dependency>

  <!-- SpringDoc OpenAPI UI -->
  <dependency>
    <groupId>org.springdoc</groupId>
    <artifactId>springdoc-openapi-starter-webmvc-ui</artifactId>
    <version>2.1.0</version> <!-- 请根据最新版本调整 -->
  </dependency>
</dependencies>

说明:springdoc-openapi-starter-webmvc-ui 会自动扫描你的 Controller 并生成 OpenAPI 3 文档,同时内置 Swagger UI。

2. (可选)自定义 OpenAPI 信息

在 Spring Boot 的配置类中,定义一个 OpenAPI Bean,用以设置标题、版本、描述等。

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
package com.example.demo.config;

import io.swagger.v3.oas.models.info.Contact;
import io.swagger.v3.oas.models.info.Info;
import io.swagger.v3.oas.models.OpenAPI;
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("v1.0")
                .description("这是一个基于 springdoc-openapi 的示例")
                .contact(new Contact()
                    .name("开发者")
                    .email("dev@example.com")
                )
            );
    }
}

3. 在 Controller 中使用注解

springdoc-openapi 支持 OpenAPI 3 注解(@Operation, @Parameter, @Schema 等):

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
package com.example.demo.controller;

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

import java.util.*;

@RestController
@RequestMapping("/api/users")
@Tag(name = "用户管理", description = "增删改查用户信息")
public class UserController {

    private final Map<Long, String> users = new HashMap<>();

    @Operation(summary = "获取所有用户")
    @GetMapping
    public List<String> listUsers() {
        return new ArrayList<>(users.values());
    }

    @Operation(summary = "根据 ID 查询用户")
    @GetMapping("/{id}")
    public String getUser(@PathVariable Long id) {
        return users.getOrDefault(id, "未找到");
    }

    @Operation(summary = "创建新用户")
    @PostMapping
    public String createUser(@RequestParam String name) {
        long id = users.size() + 1L;
        users.put(id, name);
        return "创建成功,ID=" + id;
    }

    @Operation(summary = "删除用户")
    @DeleteMapping("/{id}")
    public String deleteUser(@PathVariable Long id) {
        return users.remove(id) != null ? "删除成功" : "未找到";
    }
}

4. 运行并访问

启动 Spring Boot 应用后,打开浏览器访问:

  • Swagger UI:

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

    或

    1
    
    http://localhost:8080/swagger-ui/index.html
    
  • OpenAPI JSON/YAML:

    1
    
    http://localhost:8080/v3/api-docs
    

    (默认返回 JSON,可通过添加 .yaml 获取 YAML 格式)


二、使用 springfox-swagger2(传统方案)

注意:Springfox 对 Spring Boot 3 的支持较弱,推荐新项目使用 springdoc。以下仅供维护老项目时参考。

1. 添加依赖(Maven)

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
<dependencies>
  <!-- Spring Boot Web -->
  <dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-web</artifactId>
  </dependency>

  <!-- Springfox Swagger2 & UI -->
  <dependency>
    <groupId>io.springfox</groupId>
    <artifactId>springfox-boot-starter</artifactId>
    <version>3.0.0</version>
  </dependency>
</dependencies>

2. 配置 Swagger

在配置类中启用 Swagger 并设置文档信息:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
package com.example.demo.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import springfox.documentation.builders.ApiInfoBuilder;
import springfox.documentation.builders.PathSelectors;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.service.ApiInfo;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;

@Configuration
public class SwaggerConfig {

    @Bean
    public Docket apiDocket() {
        return new Docket(DocumentationType.SWAGGER_2)
            .select()
            .apis(RequestHandlerSelectors.basePackage("com.example.demo.controller"))
            .paths(PathSelectors.any())
            .build()
            .apiInfo(apiInfo());
    }

    private ApiInfo apiInfo() {
        return new ApiInfoBuilder()
            .title("示例 API 文档")
            .description("基于 Springfox 的 Swagger 2 文档")
            .version("v1.0")
            .build();
    }
}

3. 访问 Swagger UI

启动应用后,访问:

1
http://localhost:8080/swagger-ui/

或(根据 Springfox 版本有所不同):

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

三、总结与常见问题

  1. 推荐使用 springdoc-openapi:

    • 完整支持 OpenAPI 3,社区活跃。
    • 无需额外配置即可生成 UI。
  2. 注解支持:

    • OpenAPI 3 注解(@Operation, @Tag, @Parameter)更细粒度。
    • Springfox 则使用 Swagger 2 注解(@Api, @ApiOperation)。
  3. 安全配置: 若在接口中使用 JWT、OAuth2 等,需要额外在 OpenAPI 配置中添加安全 Schemes。例如:

     1
     2
     3
     4
     5
     6
     7
     8
     9
    10
    11
    12
    13
    
    @Bean
    public OpenAPI customOpenAPI() {
        return new OpenAPI()
          .components(new Components()
            .addSecuritySchemes("bearerAuth",
              new SecurityScheme()
                .type(SecurityScheme.Type.HTTP)
                .scheme("bearer")
                .bearerFormat("JWT")
            ))
          .addSecurityItem(new SecurityRequirement().addList("bearerAuth"))
          .info(new Info().title("带认证的 API"));
    }
    
  4. 多模块: 多个模块可通过分组(Group)方式分别生成文档。springdoc 中可使用 GroupedOpenApi。

最后更新于 2025年04月24日
使用 Hugo 构建
主题 Stack 由 Jimmy 设计