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

[Java实战]Spring Boot 整合 Swagger2 (十六)

[Java实战]Spring Boot 整合 Swagger2 (十六)

一、Swagger 的价值与痛点
为什么需要 API 文档工具?
  • 开发阶段:前后端高效协作,实时验证接口
  • 测试阶段:提供标准化测试用例
  • 维护阶段:降低新人理解成本,快速迭代
  • 对外输出:开放平台必备能力,提升开发者体验
传统文档的痛点
  • 手动维护耗时易错
  • 代码与文档割裂,更新不同步
  • 缺乏可视化测试工具
二、Spring Boot 整合 Swagger2 的 3 种姿势
1. 基础整合(5分钟极简配置)

步骤

  1. 添加依赖
<dependency><groupId>io.springfox</groupId><artifactId>springfox-swagger2</artifactId><version>2.9.2</version>
</dependency>
<dependency><groupId>io.springfox</groupId><artifactId>springfox-swagger-ui</artifactId><version>2.9.2</version>
</dependency>
  1. 配置 Swagger 主类
@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("接口统一管理说明").version("1.0").contact(new Contact("DevTeam", "https://example.com", "contact@example.com")).build();}
}
  1. 访问文档
http://localhost:8080/swagger-ui.html

在这里插入图片描述

2. 深度定制(企业级配置)

场景一:接口分组

// 后台管理接口分组
@Bean
public Docket adminApi() {return new Docket(DocumentationType.SWAGGER_2).groupName("管理后台").select().apis(input -> input.getHandlerMethod().getMethodAnnotation(AdminOnly.class) != null).build();
}// 移动端接口分组
@Bean
public Docket mobileApi() {return new Docket(DocumentationType.SWAGGER_2).groupName("移动端").select().paths(PathSelectors.ant("/api/mobile/**")).build();
}

场景二:全局参数配置

Docket docket = new Docket(...).globalOperationParameters(Arrays.asList(new ParameterBuilder().name("Authorization").description("JWT令牌").modelRef(new ModelRef("string")).parameterType("header").required(false).build()));

场景三:UI 美化(Knife4j)

<dependency><groupId>com.github.xiaoymin</groupId><artifactId>knife4j-spring-ui</artifactId><version>3.0.3</version>
</dependency>

访问地址变为:http://localhost:8080/doc.html

3. 整合 Spring Security(权限控制)

问题:Swagger 页面被拦截
解决方案

@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {@Overrideprotected void configure(HttpSecurity http) throws Exception {http.authorizeRequests().antMatchers("/swagger-ui.html").permitAll().antMatchers("/webjars/**").permitAll().antMatchers("/swagger-resources/**").permitAll().antMatchers("/v2/api-docs").permitAll().anyRequest().authenticated().and().csrf().disable();}
}
三、Swagger 注解全解析
注解作用位置核心属性
@ApiController 类tags(分组名)、description
@ApiOperation接口方法value(简述)、notes(详情)
@ApiParam方法参数name、required、example
@ApiModel实体类description
@ApiModelProperty实体类字段value、required、hidden
@ApiIgnore类/方法/参数隐藏指定元素

示例代码

@Api(tags = "用户管理", description = "注册登录相关接口")
@RestController
@RequestMapping("/user")
public class UserController {@ApiOperation("用户登录")@PostMapping("/login")public Result<User> login(@ApiParam(value = "用户名", required = true, example = "admin") @RequestParam String username,@ApiParam("密码") @RequestParam String password) {// ...}@ApiIgnore // 隐藏废弃接口@Deprecated@GetMapping("/old")public String oldMethod() { return "deprecated"; }
}
四、生产环境最佳实践
  1. 按环境开关 Swagger
@Profile({"dev", "test"}) // 只在开发测试环境启用
@Configuration
@EnableSwagger2
public class SwaggerConfig { ... }
  1. 敏感接口过滤
Docket docket = new Docket(...).select().apis(Predicates.not(RequestHandlerSelectors.withMethodAnnotation(InternalApi.class))).build();
  1. 文档导出离线使用
  • 访问 /v2/api-docs 获取 JSON
  • 使用 Swagger Editor 导入生成 HTML
  1. 版本升级建议
  • Swagger2:维护模式,适合已有项目
  • SpringDoc(Swagger3):新项目推荐,支持 OpenAPI 3.0
    <dependency><groupId>org.springdoc</groupId><artifactId>springdoc-openapi-ui</artifactId><version>1.6.9</version>
    </dependency>
    
五、高频问题排查
问题现象原因分析解决方案
访问 404路径被拦截或依赖缺失检查安全配置,确认依赖版本正确
模型字段未显示未添加 @ApiModelProperty检查注解并设置 hidden = false
接口描述乱码响应头未指定编码添加 @RequestMapping(produces = "application/json;charset=UTF-8")
文件上传参数异常Swagger 默认表单类型限制添加 @ApiParam 并指定 dataType = "__File"
六、总结

Spring Boot 整合 Swagger2 能够显著提升 API 管理效率,但需注意:

  • 开发阶段:合理使用注解增强文档可读性
  • 测试阶段:利用 UI 快速验证接口逻辑
  • 生产环境:严格管控文档访问权限,避免信息泄露

附录

  • Swagger 官方文档
  • SpringDoc 迁移指南
  • Knife4j 增强方案

希望本教程对您有帮助,请点赞❤️收藏⭐关注支持!欢迎在评论区留言交流技术细节!

http://www.xdnf.cn/news/409555.html

相关文章:

  • 面试题:C++虚函数可以是内联函数吗?
  • 如何选择和实施PLM系统以提升企业效率?三品PLM系统:驱动企业效率跃升
  • 专业课复习笔记 9
  • 【记录nginx请求头参数丢失问题】
  • Android学习总结之布局篇
  • 《算法导论(第4版)》阅读笔记:p32-p38
  • Git常用操作
  • 测试文章标题01
  • 安装Hadoop并运行WordCount程序
  • 在IDEA中导入gitee项目
  • MySQL 8.0 OCP 1Z0-908 题目解析(1)
  • CSS3 伪类和使用场景
  • Matlab 列车纵向滑模二阶自抗扰算法和PID对比
  • 2025爬虫实战技巧:高效数据采集方案
  • 云境天合土壤含水量监测仪器—查看土壤水分数据,掌握土壤墒情变化
  • Java 语法基础(笔记)
  • 如何查看项目是否支持最新 Android 16K Page Size 一文汇总
  • React中的useSyncExternalStore使用
  • 面向对象的js
  • 短视频兴趣算法的实现原理与技术架构
  • Linux512 ssh免密登录 ssh配置回顾
  • 写项目遇到的通用问题
  • Windows 安装 Milvus
  • 论坛项目测试
  • Matlab 模糊pid控制的永磁同步电机PMSM
  • 前端面经 计网 http和https区别
  • ​Spring Boot 配置文件敏感信息加密:Jasypt 实战
  • 国产密码新时代!华测国密 SSL 证书解锁安全新高度
  • 开疆智能canopen转Profinet网关连接AGV磁钉读头配置案例
  • HTTP2