使用 springdoc-openapi-ui
时间: 2025-06-03 10:18:40 浏览: 21
### Spring Boot 集成 springdoc-openapi-ui 替代 Springfox 的配置调整和代码示例
#### 1. 引入依赖
在 `pom.xml` 文件中,移除与 Springfox 相关的依赖,并添加以下 `springdoc-openapi-ui` 依赖:
```xml
<dependency>
<groupId>org.springdoc</groupId>
<artifactId>springdoc-openapi-ui</artifactId>
<version>1.6.11</version>
</dependency>
```
此版本兼容 Spring Boot 2.5.15[^3]。
#### 2. 删除旧配置
删除原有的 Springfox 配置类,例如 `SwaggerConfig.java` 和启动类中的 `@EnableSwagger2` 注解。这些配置不再需要,因为 `springdoc-openapi-ui` 会自动集成到 Spring MVC 应用中[^1]。
#### 3. 新配置类(可选)
虽然 `springdoc-openapi-ui` 不需要额外的配置类,但可以通过 `application.properties` 或 `application.yml` 进行自定义配置。例如:
```properties
# application.properties
springdoc.api-docs.path=/v3/api-docs
springdoc.swagger-ui.path=/swagger-ui.html
```
或者使用 YAML 格式:
```yaml
# application.yml
springdoc:
api-docs:
path: /v3/api-docs
swagger-ui:
path: /swagger-ui.html
```
这些配置项分别指定了 API 文档和 Swagger UI 的访问路径[^4]。
#### 4. 启动类调整
确保启动类上没有多余的注解冲突,例如:
```java
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class DemoApplication {
public static void main(String[] args) {
SpringApplication.run(DemoApplication.class, args);
}
}
```
#### 5. 访问 Swagger UI
启动项目后,访问以下地址查看 Swagger UI 页面:
```
http://localhost:8080/v3/api-docs
http://localhost:8080/swagger-ui.html
```
如果页面无法加载,请检查是否启用了安全框架(如 Spring Security),这可能会阻止访问 Swagger 资源[^5]。
#### 6. 示例代码
以下是一个简单的控制器示例,展示如何使用 `springdoc-openapi-ui` 自动生成文档:
```java
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.media.Content;
import io.swagger.v3.oas.annotations.media.Schema;
import io.swagger.v3.oas.annotations.responses.ApiResponse;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
@RestController
@RequestMapping("/api")
@Tag(name = "Sample Controller", description = "API for sample operations")
public class SampleController {
@Operation(summary = "Fetch greeting message", description = "Returns a simple greeting message based on the provided name",
responses = {
@ApiResponse(responseCode = "200", description = "Successful operation",
content = @Content(schema = @Schema(implementation = String.class)))
})
@GetMapping("/greeting")
public String getGreeting(@RequestParam(required = false, defaultValue = "World") String name) {
return "Hello, " + name + "!";
}
}
```
#### 7. 常见问题解决
- **问题:接口文档生成不完整或为空。**
- 确保控制器类被正确扫描,并且方法上有适当的注解(如 `@Operation` 和 `@Parameter`)[^6]。
- **问题:Swagger 文档无法加载。**
- 检查依赖版本是否正确,以及是否存在其他冲突的依赖项。
---
阅读全文
相关推荐


















