让API开口说话,Swagger如何把枯燥代码变成“活文档”

62 阅读5分钟

大家好,我是小悟。

有没有遇到过这样的尴尬场景?

前端小妹跑来问你:“哥哥,这个用户列表接口怎么调用呀?” 你自信满满:“看文档啊!” 然后她发来一张截图——你去年写的Word文档,上面写着:

GET /api/users (大概是这个吧,我也忘了)
可能需要token,不确定
参数...自己猜吧

这时候你就需要Swagger——它就像是给你的API开了个24小时真人直播秀,让前端、测试、甚至产品经理都能直接看到每个接口的“素颜”状态!

什么是Swagger?

想象一下,你的API是个害羞的宅男,从来不出门见人。Swagger就是那个逼他:

  1. 穿上西装(自动生成文档)
  2. 站在聚光灯下(可视化界面)
  3. 还自带使用说明书(在线测试)

最妙的是,这哥们还会自动更新!代码一改,文档立刻变,再也不用担心“文档版本落后于代码”这种史诗级bug了。

开始整活!SpringBoot集成Swagger详细步骤

第1步:添加依赖——给项目“注射美容针”

<!-- pom.xml 里加入这些“营养品” -->
<dependency>
    <groupId>io.springfox</groupId>
    <artifactId>springfox-boot-starter</artifactId>
    <version>3.0.0</version>
</dependency>

<!-- 如果你用的是Swagger3(推荐) -->
<dependency>
    <groupId>io.springfox</groupId>
    <artifactId>springfox-boot-starter</artifactId>
    <version>3.0.0</version>
</dependency>

或者用Gradle的小伙伴:

// 在build.gradle里“加点料”
implementation 'io.springfox:springfox-boot-starter:3.0.0'

第2步:创建配置类——给Swagger“办个身份证”

package com.example.demo.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import springfox.documentation.builders.ApiInfoBuilder;
import springfox.documentation.builders.PathSelectors;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.service.ApiInfo;
import springfox.documentation.service.Contact;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;

@Configuration
public class SwaggerConfig {
    
    @Bean
    public Docket createRestApi() {
        return new Docket(DocumentationType.OAS_30)
                .apiInfo(apiInfo())
                .select()
                // 扫描的包路径,就像告诉Swagger:“去这个包厢找人”
                .apis(RequestHandlerSelectors.basePackage("com.example.demo.controller"))
                // 扫描所有路径,相当于“这个KTV所有房间都看看”
                .paths(PathSelectors.any())
                .build()
                .enable(true) // 想关闭Swagger时改成false,就像“今天不营业”
                .groupName("默认分组"); // 可以分多个组,就像给API分班级
    }
    
    private ApiInfo apiInfo() {
        return new ApiInfoBuilder()
                .title("API文档标题")
                .description("""
                    这里是详细的描述,可以写很长很长...
                    比如:
                    1. 这个系统是干什么的
                    2. 接口有什么特殊要求
                    3. 常见的错误码说明
                    
                    支持Markdown语法哦!
                    """)
                .contact(new Contact(
                    "你的名字", 
                    "https://github.com/yourname", 
                    "your.email@example.com"
                ))
                .version("v1.0.0")
                .license("MIT License")
                .licenseUrl("https://opensource.org/licenses/MIT")
                .termsOfServiceUrl("http://localhost:8080")
                .build();
    }
}

第3步:Controller添加注解——给API“化妆打扮”

package com.example.demo.controller;

import io.swagger.annotations.*;
import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping("/api/users")
@Api(tags = "用户管理模块", value = "用户相关的所有操作")
public class UserController {
    
    @GetMapping("/{id}")
    @ApiOperation(value = "根据ID查询用户", notes = "注意:id必须是正整数")
    @ApiImplicitParams({
        @ApiImplicitParam(
            name = "id", 
            value = "用户ID", 
            required = true, 
            dataType = "Long", 
            paramType = "path",
            example = "123"
        )
    })
    @ApiResponses({
        @ApiResponse(code = 200, message = "成功"),
        @ApiResponse(code = 404, message = "用户不存在"),
        @ApiResponse(code = 500, message = "服务器开小差了")
    })
    public User getUser(@PathVariable Long id) {
        // 你的业务逻辑
        return userService.findById(id);
    }
    
    @PostMapping("/")
    @ApiOperation(value = "创建用户", notes = "创建一个新用户")
    public User createUser(
            @ApiParam(value = "用户对象", required = true) 
            @RequestBody UserDTO userDTO) {
        return userService.create(userDTO);
    }
    
    // 实体类也要加注解,这样Swagger才知道字段的含义
    @ApiModel(description = "用户实体")
    public static class User {
        @ApiModelProperty(value = "用户ID", example = "1")
        private Long id;
        
        @ApiModelProperty(value = "用户名", example = "张三", required = true)
        private String username;
        
        @ApiModelProperty(value = "邮箱", example = "zhangsan@example.com")
        private String email;
        
        // getters and setters
    }
}

第4步:配置文件调整——解决“404尴尬症”

# application.yml
spring:
  mvc:
    pathmatch:
      matching-strategy: ant_path_matcher  # 解决SpringBoot2.6+的兼容问题

# 如果想自定义Swagger路径
springfox:
  documentation:
    swagger-ui:
      path: /swagger-ui.html  # 默认就是这个
      enabled: true

第5步:启动并访问——见证奇迹的时刻!

  1. 启动SpringBoot应用
  2. 打开浏览器访问:http://localhost:8080/swagger-ui/
  3. 或者访问:http://localhost:8080/swagger-ui/index.html

你会看到一个漂亮的界面,左边是API列表,右边是详细说明,还可以直接点击“Try it out”测试接口!

高级玩法——给Swagger“加特效”

1. 分组显示(适合微服务)

@Bean
public Docket userApi() {
    return new Docket(DocumentationType.OAS_30)
            .groupName("用户模块")
            .select()
            .apis(RequestHandlerSelectors.basePackage("com.example.user"))
            .build();
}

@Bean
public Docket orderApi() {
    return new Docket(DocumentationType.OAS_30)
            .groupName("订单模块")
            .select()
            .apis(RequestHandlerSelectors.basePackage("com.example.order"))
            .build();
}

2. 添加全局token

@Bean
public Docket createRestApi() {
    return new Docket(DocumentationType.OAS_30)
            .securitySchemes(Collections.singletonList(
                new ApiKey("Authorization", "Authorization", "header")
            ))
            // ...其他配置
}

3. 自定义响应消息

@Bean
public Docket createRestApi() {
    return new Docket(DocumentationType.OAS_30)
            .globalResponses(HttpMethod.GET, Arrays.asList(
                new ResponseBuilder()
                    .code("500")
                    .description("服务器内部错误")
                    .build(),
                new ResponseBuilder()
                    .code("403")
                    .description("没有权限")
                    .build()
            ))
            // ...其他配置
}

常见问题及解决方案

问题1:访问/swagger-ui/报404

解决方案:
1. 检查依赖是否正确
2. 添加@EnableOpenApi注解(Swagger3)
3. 检查SpringBoot版本兼容性

问题2:界面出来了,但没显示API

解决方案:
1. 检查@RestController是否在扫描包内
2. 检查@RequestMapping等注解是否正确
3. 检查Docket配置的路径选择器

问题3:生产环境想关闭Swagger

# application-prod.yml
springfox:
  documentation:
    enabled: false

或者用Profile控制:

@Profile({"dev", "test"})  // 只在开发测试环境生效
@Configuration
public class SwaggerConfig {
    // 配置内容
}

总结:Swagger到底香不香?

优点(为什么你要用):

  1. 自动生成文档:代码即文档,改了代码文档自动更新,告别“文档滞后”
  2. 在线测试:前端不用等你了,自己就能测试接口
  3. 协作神器:前后端对接再也不用“传纸条”
  4. 支持多种格式:可以导出JSON、YAML等格式
  5. 社区活跃:遇到问题容易找到解决方案

缺点(你要注意的):

  1. 代码侵入性:注解会让Controller看起来有点“胖”
  2. 性能影响:生产环境建议关闭
  3. 学习成本:各种注解需要时间熟悉

最后:

  • 小项目用Swagger,就像给自行车装导航——方便!
  • 大项目用Swagger,就像给航母装GPS——必须!
  • 不用Swagger,就像开车不看路标——容易撞墙!

好的API文档不是写出来的,是“生成”出来的。Swagger就是你的API的专属化妆师+摄影师+经纪人,让你的接口从“代码宅男”变身“流量明星”!

现在给你的SpringBoot项目装上Swagger吧,让前端妹子对你刮目相看!

让API开口说话,Swagger如何把枯燥代码变成“活文档”.png

谢谢你看我的文章,既然看到这里了,如果觉得不错,随手点个赞、转发、在看三连吧,感谢感谢。那我们,下次再见。

您的一键三连,是我更新的最大动力,谢谢

山水有相逢,来日皆可期,谢谢阅读,我们再会

我手中的金箍棒,上能通天,下能探海