Skip to content

快速开始

阅读前提

  • JDK 17+
  • Spring Boot 3.x
  • 已引入 forge-core(或至少 forge-apiforge-processor

三步上手

1. 引入依赖

xml
<dependency>
    <groupId>cn.cvking</groupId>
    <artifactId>forge-swagger</artifactId>
    <version>1.0.0</version>
</dependency>

模块本身已经把 springdoc-openapi-starter-webmvc-uiknife4j-openapi3-jakarta-spring-boot-starter 作为依赖打包,业务方无需再单独引入。

2. 启动应用

无需任何配置。SwaggerConfig 通过 @Configuration 自动注册,前提是业务工程的启动类能扫到 cn.cvking.forge(与 core 模块的扫描要求一致)。

3. 访问文档

启动应用后,两套 UI 可任选:

UI路径风格
原生 Swagger UIhttp://localhost:18080/swagger-ui.htmlSpringdoc 默认
Knife4jhttp://localhost:18080/doc.html国内常见的中文增强

端口号

默认服务器 URL 在 SwaggerConfig 里硬编码为 http://localhost:18080。如果你的服务在其它端口,详见 配置说明 · 覆盖默认 OpenAPI Bean

看到自动包裹的 Result

写一个最简单的 Controller:

java
@RestController
@RequestMapping("/user")
public class UserController {

    @GetMapping("/{id}")
    public UserDTO getById(@PathVariable Long id) {
        return new UserDTO(id, "张三", 25);
    }
}

进入 Knife4j 看到的响应 schema 不是 UserDTO,而是:

json
{
  "success": true,
  "code": 200,
  "message": "操作成功",
  "data": {
    "id": 1,
    "username": "张三",
    "email": "zhangsan@example.com",
    "age": 25,
    "phone": "13800138001"
  }
}

文档里的 schema 名是 Result«UserDTO»,与实际响应完全对齐。

看到 @RawResponse 被尊重

java
@GetMapping("/raw")
@RawResponse
public String raw() {
    return "原始字符串";
}

这个接口在 Knife4j 中的响应 schema 不会被 Result 包裹,与运行时的 @RawResponse 行为保持一致。

实现细节见 设计文档 · 响应包装定制器