Spring Boot 3 整合 springdoc-openapi
概述
springdoc-openapi
是一个用于自动生成 OpenAPI 3.0 文档的库,它支持与 Spring Boot 无缝集成。通过这个库,你可以轻松地生成和展示 RESTful API 的文档,并且可以使用 Swagger UI 或 ReDoc 进行交互式测试。
环境准备
- Spring Boot 3.x
- Java 17+
- Maven
创建 Spring Boot 项目
首先,创建一个新的 Spring Boot 项目。你可以使用 Spring Initializr 来快速生成项目结构。
添加依赖
在 pom.xml
文件中添加 springdoc-openapi-ui
依赖:
<dependencies>
<!-- Spring Web 依赖 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<!-- springdoc-openapi-starter-webmvc-ui 是一个 Spring Boot Starter,它包含了 springdoc-openapi-ui 及其他必要的依赖,简化了依赖管理和配置 -->
<dependency>
<groupId>org.springdoc</groupId>
<artifactId>springdoc-openapi-starter-webmvc-ui</artifactId>
<version>2.6.0</version>
</dependency>
<!-- springdoc-openapi-ui 依赖 -->
<!-- <dependency>-->
<!-- <groupId>org.springdoc</groupId>-->
<!-- <artifactId>springdoc-openapi-ui</artifactId>-->
<!-- <version>1.8.0</version>-->
<!-- </dependency>-->
</dependencies>
配置文件
在 application.yml
或 application.properties
中配置 Swagger UI 和 ReDoc 的路径(可选):
springdoc:
api-docs:
path: /v3/api-docs
swagger-ui:
path: /swagger-ui.html
enabled: true
operationsSorter: method
show-actuator: true
或者在 application.properties
中:
springdoc.api-docs.path=/v3/api-docs
springdoc.swagger-ui.path=/swagger-ui.html
springdoc.swagger-ui.enabled=true
springdoc.swagger-ui.operations-sorter=method
springdoc.show-actuator=true
创建模型类
创建一个简单的模型类 User
,并使用 @Schema
注解来描述字段:
package org.springdoc.demo.services.user.model;
import io.swagger.v3.oas.annotations.media.Schema;
@Schema(name = "User", description = "用户实体")
public class User {
@Schema(description = "用户ID", example = "1", requiredMode = Schema.RequiredMode.REQUIRED)
private Long id;
@Schema(description = "用户名", example = "john_doe", requiredMode = Schema.RequiredMode.REQUIRED)
private String username;
@Schema(description = "电子邮件", example = "john.doe@example.com", requiredMode = Schema.RequiredMode.REQUIRED)
private String email;
public User(Long id, String username, String email) {
this.id = id;
this.username = username;
this.email = email;
}
public Long getId() {
return id;