Swagger UI 是一个强大的工具,能够自动生成 API 文档,帮助开发者更高效地展示和测试接口。以下是快速上手指南:
🚀 快速入门
安装配置
在 Spring Boot 项目中添加依赖:<dependency> <groupId>io.springfox</groupId> <artifactId>springfox-swagger2</artifactId> <version>2.9.2</version> </dependency>
配置 Swagger 信息:
@Bean public Docket api() { return new Docket(DocumentationType.SWAGGER_2) .select() .apis(RequestHandlerSelectors.basePackage("com.example.api")) .paths(PathSelectors.any()) .build(); }
启动服务
访问http://localhost:8080/swagger-ui.html
即可查看自动生成的文档界面。
📚 使用示例
- 定义接口
使用@ApiOperation
注解描述接口功能:@GetMapping("/users") @ApiOperation("获取用户列表") public List<User> getUsers() { // 实现逻辑 }
- 参数说明
通过@ApiParam
注解详细说明每个参数:@ApiParam(name = "id", value = "用户ID", example = "123")
🎨 自定义功能
- 主题样式
修改swagger-ui.html
的springfox.documentation.swagger.v2.web.SwaggerUiConfigParameters
可自定义界面主题。 - 认证配置
添加@ApiAuthorization
注解实现 API 认证功能,如 JWT 或 OAuth2。
📁 扩展阅读
📌 提示:确保你的 API 文档包含完整路径和参数说明,以提升用户体验!