springdoc-openapi-starter-webmvc-ui使用
时间: 2025-05-07 20:04:21 浏览: 169
### 如何配置和使用 `springdoc-openapi-starter-webmvc-ui`
`springdoc-openapi-starter-webmvc-ui` 是一个强大的工具,能够帮助开发者快速生成基于 OpenAPI 3 的 API 文档并集成了 Swagger UI 功能。以下是详细的配置和使用方法:
#### 1. 添加 Maven 或 Gradle 依赖
为了在项目中启用 `springdoc-openapi-starter-webmvc-ui`,需要将其作为依赖项添加到项目的构建文件中。
对于 **Maven** 用户,在 `pom.xml` 文件中加入以下内容:
```xml
<dependency>
<groupId>org.springdoc</groupId>
<artifactId>springdoc-openapi-starter-webmvc-ui</artifactId>
<version>2.2.0</version>
</dependency>
```
此版本号可以根据实际需求调整[^2]。
对于 **Gradle** 用户,则可以在 `build.gradle` 中添加如下代码:
```gradle
implementation 'org.springdoc:springdoc-openapi-starter-webmvc-ui:2.2.0'
```
#### 2. 启动类上的注解支持
确保 Spring Boot 应用程序的启动类上已经标注了 `@SpringBootApplication` 注解。如果应用程序涉及多个模块或者复杂的上下文加载逻辑,可以额外确认是否需要其他特定的扫描路径设置。
#### 3. 自定义 Swagger UI 路径(可选)
默认情况下,Swagger UI 可通过访问 `/swagger-ui/index.html` 来查看。然而,可以通过修改 `application.properties` 或者 `application.yml` 文件来自定义其路径。例如:
在 `application.properties` 文件中:
```properties
springdoc.swagger-ui.path=/custom-swagger-path
```
这会使得新的访问 URL 成为:`http://localhost:<port>/custom-swagger-path`[^3]。
#### 4. 基本控制器示例
创建一个简单的 REST 控制器以验证功能是否正常工作。下面是一个基本的例子:
```java
import io.swagger.v3.oas.annotations.Operation;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
@RequestMapping("/example")
public class ExampleController {
@Operation(summary = "获取示例数据", description = "这是一个用于演示 springdoc-openapi 的接口")
@GetMapping("/data")
public String getData() {
return "Hello, Springdoc!";
}
}
```
上述代码中的 `@Operation` 注解提供了关于该端点的具体描述信息,这些信息将会显示在生成的文档页面上[^4]。
#### 5. 运行应用并访问 Swagger UI 页面
完成以上步骤之后,运行 Spring Boot 应用程序,并打开浏览器输入地址栏指向本地服务器实例下的指定路径,默认应为 `http://localhost:8080/swagger-ui/index.html`。此时应该可以看到完整的交互式 API 列表以及说明文档[^5]。
---
### 注意事项
- 如果遇到任何 CORS 相关错误,请检查是否有适当的安全策略允许跨域请求。
- 对于生产环境部署建议关闭敏感信息暴露的功能以防潜在风险。
阅读全文
相关推荐



















