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

发布于:2025-05-13 ⋅ 阅读:(18) ⋅ 点赞:(0)

[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 {
    @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")
                .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 {

    @Override
    protected 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 注解全解析
注解 作用位置 核心属性
@Api Controller 类 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 快速验证接口逻辑
  • 生产环境:严格管控文档访问权限,避免信息泄露

附录

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


网站公告

今日签到

点亮在社区的每一天
去签到