使用 Smart-Doc 生成 API 文档

Smart-Doc 是一款支持 Java REST API、Java WebSocket、Apache Dubbo RPC 和 gRPC 接口文档生成的工具。它对项目可以算是零侵入,不需要像 Swagger 一样引入一大堆注解,学习成本也很低,只需要写好标准的 Java 注释。

下面以我自己的项目(SpringBoot 项目)为例,介绍如何使用 Smart-Doc 生成 API 文档。

第一步:创建配置文件

在项目启动类所在模块的 resources 目录下创建 smart-doc.json 文件,示例配置如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
{
"outPath": "./src/main/resources/static/doc",
"isStrict": false,
"allInOne": true,
"createDebugPage": false,
"packageFilters": "com.yohlj.app.atom.controller.admin.*,com.yohlj.app.atom.controller.general.*",
"style": "xt256",
"projectName": "atom-api-doc",
"allInOneDocFileName": "index.html",
"requestHeaders": [
{
"name": "x-access-token",
"type": "string",
"desc": "登录状态访问令牌",
"required": true
}
]
}

配置项释义详见官方文档,当然也可以使用最小化配置,后续根据需要增加其他配置,最小化配置如下:

1
2
3
{
"outPath": "./src/main/resources/static/doc"
}

第二步:配置 Maven 插件

在项目启动类所在模块的 pom.xml 文件配置 Maven 插件,注意: 需要 includes 依赖的源码包,pom 配置示例:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
<plugin>
<groupId>com.github.shalousun</groupId>
<artifactId>smart-doc-maven-plugin</artifactId>
<version>2.7.7</version>
<configuration>
<configFile>./src/main/resources/smart-doc.json</configFile>
<projectName>atom-api-doc</projectName>
<includes>
<include>com.yohlj.app:atom</include>
</includes>
</configuration>
<executions>
<execution>
<!--如果不需要在执行编译时启动smart-doc,则将phase注释掉-->
<phase>compile</phase>
<goals>
<!--smart-doc提供了html、openapi、markdown等goal,可按需配置-->
<goal>html</goal>
</goals>
</execution>
</executions>
</plugin>

第三步:生成文档

Maven Reload 一下,发现多了个 smart-doc 插件,点击它我们就可进行文档的生成。

接着,在 smart-doc.json 文件配置的路径下,我们发现了生成的 HTML,打开看看效果:

第四步(可选):通过后端服务访问文档

如果将接口文档存放在 resources 目录下,想通过后端服务来访问到它,需要做以下配置:

1
2
3
4
spring:
web:
resources:
add-mappings: true

这样,你就可以通过后端服务访问生成的 API 文档了。


使用 Smart-Doc 生成 API 文档
https://blog.yohlj.cn/posts/64dc22b7/
作者
Enoch
发布于
2024年5月6日
许可协议