1. 什么是 Swagger2Swagger2 是一套基于 OpenAPI 规范的开源工具集用于设计、构建、文档化和消费 RESTful Web 服务。它通过注解和代码生成让 API 文档与代码保持同步极大提升了前后端协作效率。2. 核心优势代码即文档通过注解自动生成 API 文档避免手动维护带来的不一致问题。交互式测试提供 Web UI 界面可直接在浏览器中调用接口进行测试。多语言支持支持 Java、.NET、Node.js、Python 等多种后端语言。规范统一遵循 OpenAPI 规范便于与其他工具链集成。3. 快速集成Spring Boot 示例3.1 添加依赖dependency groupIdio.springfox/groupId artifactIdspringfox-swagger2/artifactId version2.9.2/version /dependency dependency groupIdio.springfox/groupId artifactIdspringfox-swagger-ui/artifactId version2.9.2/version /dependency3.2 配置类Configuration EnableSwagger2 public class SwaggerConfig { Bean public 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(用户管理模块接口文档) .version(1.0) .build(); } }3.3 常用注解Api标注在 Controller 类上说明该类的作用ApiOperation标注在方法上说明接口功能ApiParam标注在参数上说明参数含义ApiModel标注在实体类上说明模型信息ApiModelProperty标注在实体字段上说明字段信息4. 实战示例4.1 用户管理接口RestController RequestMapping(/api/users) Api(tags 用户管理) public class UserController { PostMapping ApiOperation(创建用户) public ResponseEntityUser createUser(RequestBody Valid User user) { // 业务逻辑 return ResponseEntity.ok(user); } GetMapping(/{id}) ApiOperation(根据ID查询用户) public ResponseEntityUser getUserById( PathVariable ApiParam(用户ID) Long id) { // 业务逻辑 return ResponseEntity.ok(new User()); } }4.2 实体类示例ApiModel(用户信息) public class User { ApiModelProperty(value 用户ID, example 1) private Long id; ApiModelProperty(value 用户名, required true, example 张三) private String username; ApiModelProperty(value 邮箱, example zhangsanexample.com) private String email; // getters and setters }5. 访问与使用启动应用后通过以下地址访问 Swagger UISwagger UIhttp://localhost:8080/swagger-ui.htmlAPI 文档 JSONhttp://localhost:8080/v2/api-docs6. 注意事项生产环境建议关闭 Swagger或通过权限控制访问注意注解的合理使用避免过度注解导致代码冗余及时更新依赖版本关注安全漏洞修复结合 Spring Security 可实现接口访问权限控制7. 总结Swagger2 作为 RESTful API 文档生成工具通过注解驱动的方式实现了代码与文档的同步更新大大提升了开发效率。结合 Spring Boot 可以快速集成为团队协作和接口测试提供了便利。随着 OpenAPI 3.0 的发展也可以考虑迁移到 SpringDoc OpenAPI 等新一代工具。