当前位置: 首页 > news >正文

Swagger 配置及使用指南

Spring Boot 项目集成 Swagger 配置及使用指南

一、Swagger 简介

Swagger 是一个用于设计、构建、文档化和使用 RESTful API 的框架。通过集成 Swagger,开发者可以:

  • 自动生成实时 API 文档
  • 直接在浏览器中测试 API 接口
  • 减少手动编写文档的工作量
  • 支持团队协作开发

二、环境配置(Spring Boot 2.7.x 示例)

1. 添加 Maven 依赖

<!-- pom.xml -->
<dependency><groupId>io.springfox</groupId><artifactId>springfox-swagger2</artifactId><version>3.0.0</version>
</dependency>
<dependency><groupId>io.springfox</groupId><artifactId>springfox-swagger-ui</artifactId><version>3.0.0</version>
</dependency>

2. 创建配置类

@Configuration
@EnableSwagger2
public class SwaggerConfig {@Beanpublic Docket api() {return new Docket(DocumentationType.SWAGGER_2).select().apis(RequestHandlerSelectors.basePackage("com.example.controller")) // 指定扫描包.paths(PathSelectors.any()).build().apiInfo(apiInfo());}private ApiInfo apiInfo() {return new ApiInfoBuilder().title("API 文档").description("Spring Boot 集成 Swagger 示例").version("1.0.0").contact(new Contact("开发者", "https://example.com", "contact@example.com")).build();}
}

3. 解决常见启动问题

# application.yml
spring:mvc:pathmatch:matching-strategy: ANT_PATH_MATCHER # 解决 Spring Boot 2.6+ 版本问题

三、Swagger 注解使用

1. Controller 层注解

@RestController
@Api(tags = "用户管理接口")
@RequestMapping("/api/users")
public class UserController {@ApiOperation(value = "获取用户详情", notes = "根据ID查询用户信息")@GetMapping("/{id}")public ResponseEntity<User> getUser(@ApiParam(value = "用户ID", required = true, example = "1") @PathVariable Long id) {// 业务逻辑}
}

2. Model 层注解

@ApiModel(description = "用户实体")
public class User {@ApiModelProperty(value = "用户ID", example = "1001")private Long id;@ApiModelProperty(value = "用户名", required = true, example = "john_doe")private String username;// getters/setters
}

四、访问与测试

1. 访问文档页面

启动项目后访问:

http://localhost:8080/swagger-ui/index.html

2. 接口测试示例

  1. 在 Swagger UI 中找到目标接口
  2. 点击 “Try it out”
  3. 输入请求参数
  4. 点击 “Execute” 发送请求
  5. 查看响应结果和状态码

五、高级配置(可选)

1. 安全配置

// 允许访问 Swagger 资源
@Configuration
public class WebConfig implements WebMvcConfigurer {@Overridepublic void addResourceHandlers(ResourceHandlerRegistry registry) {registry.addResourceHandler("/swagger-ui/**").addResourceLocations("classpath:/META-INF/resources/webjars/springfox-swagger-ui/");}
}

2. 分组配置

// 创建多个 API 分组
@Bean
public Docket adminApi() {return new Docket(DocumentationType.SWAGGER_2).groupName("管理端接口").select().apis(RequestHandlerSelectors.basePackage("com.example.admin")).build();
}

六、最佳实践建议

  1. 在开发环境开启 Swagger,生产环境建议关闭
  2. 使用 @ApiIgnore 忽略不需要展示的接口
  3. 保持文档与代码同步更新
  4. 为每个参数添加示例值(example)
  5. 合理使用响应状态码描述

七、常见问题解决

  1. 页面404:检查依赖版本是否冲突
  2. 接口未显示:确认包扫描路径正确
  3. 参数类型错误:添加 @RequestParam/@PathVariable 注解
  4. 日期格式问题:在配置中添加全局日期格式

通过以上配置和使用方法,开发者可以快速在 Spring Boot 项目中集成 Swagger,显著提升 API 开发效率。建议结合实际项目需求灵活运用各种注解,并定期查看生成的文档验证准确性。

http://www.dtcms.com/a/300283.html

相关文章:

  • Redis C++客户端——通用命令
  • 多模态大模型与 AI 落地:从技术原理到实践路径的深度解析
  • 力扣刷题(第九十九天)
  • 【C语言进阶】程序环境和预处理
  • [Python 基础课程]注释
  • C++高效实现AI人工智能实例
  • IntelliJ IDEA 中左上方未显示项目根目录问题
  • 网络:基础概念
  • GLSL 3.0简介
  • [RPA] 日期时间练习案例
  • Xinference vs SGLang:详细对比分析
  • 最优估计准则与方法(4)最小二乘估计(LS)_学习笔记
  • 【补题】Codeforces Global Round 15 B. Running for Gold
  • P1019 [NOIP 2000 提高组] 单词接龙
  • 从Python编程到AI大模型:GeoAI大模型驱动的地球科学智能计算——涵盖随机森林、CNN、LSTM、Transformer及科研绘图实战
  • linux mmc驱动精讲-1、引言
  • UNet改进(25):集成可变形注意力的高效图像分割方法
  • python 检测蜂窝网络,实现掉网自动拨号
  • nacos启动报错:Unable to start embedded Tomcat。
  • ChatIm项目文件上传与获取
  • 配置nodejs
  • 面试150 数据流的中位数
  • 6.数组和字符串
  • 从稀疏数据(CSV)创建非常大的 GeoTIFF(和 WMS)
  • 【时时三省】(C语言基础)返回指针值的函数
  • TRIM功能
  • 《代码随想录》刷题记录
  • 速通python加密之MD5加密
  • Datawhale AI 夏令营:让AI理解列车排期表 Notebook(Baseline拆解)
  • JVM常见工具