一、为什么需要 swagger?
在前后端分离的开发模式下,api 文档是前后端沟通的桥梁。传统的手写文档不仅维护成本高,还容易与代码脱节。swagger 允许开发者在代码中通过注解生成在线接口文档,并可直接在页面中调试接口,极大提升了团队的协作效率。
二、环境与工具准备
本文基于 spring boot 2.7.x 和 java 8+,使用 springfox(swagger 的 java 实现)来集成 swagger。如果你是 spring boot 3.x,请使用 springdoc-openapi,本文也会在最后给出兼容方案。
首先创建一个 spring boot 项目,并在 pom.xml 中添加依赖:
<!-- spring boot 2.x 中使用 springfox -->
<dependency>
<groupid>io.springfox</groupid>
<artifactid>springfox-boot-starter</artifactid>
<version>3.0.0</version>
</dependency>如果是 spring boot 2.1.x 及以下,可能需要额外引入 springfox-swagger-ui 等依赖,但本文推荐使用 starter 方式,简化配置。
三、快速上手:第一个 swagger 配置
在 spring boot 项目中新建一个配置类 swaggerconfig,并启用 swagger:
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.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()
.apis(requesthandlerselectors.basepackage("com.example.demo.controller"))
.paths(pathselectors.any())
.build();
}
private apiinfo apiinfo() {
return new apiinfobuilder()
.title("swagger 实战教程 api 文档")
.description("这是一份详细的 swagger 集成示例")
.version("1.0.0")
.build();
}
}- documentationtype.oas_30:使用 openapi 3.0 规范,swagger 3 默认使用。
- basepackage:指定扫描的 controller 包,避免扫描到无关接口。
- paths:可以限定接口路径,这里选择所有路径。
启动项目后,访问 http://localhost:8080/swagger-ui/index.html,即可看到 swagger ui 页面。
四、核心注解实战
创建一个简单的用户管理 controller,演示常用注解:
import com.example.demo.entity.user;
import io.swagger.annotations.api;
import io.swagger.annotations.apioperation;
import io.swagger.annotations.apiparam;
import org.springframework.web.bind.annotation.*;
@restcontroller
@requestmapping("/users")
@api(tags = "用户管理")
public class usercontroller {
@getmapping("/{id}")
@apioperation(value = "根据 id 查询用户", notes = "返回用户详细信息")
public user getuserbyid(
@apiparam(value = "用户 id", required = true, example = "101")
@pathvariable long id) {
return new user(id, "张三", "zhangsan@example.com");
}
@postmapping
@apioperation("创建用户")
public user createuser(@requestbody user user) {
return user;
}
}对应的实体类 user:
import io.swagger.annotations.apimodel;
import io.swagger.annotations.apimodelproperty;
@apimodel(description = "用户实体")
public class user {
@apimodelproperty(value = "用户 id", example = "1")
private long id;
@apimodelproperty(value = "用户名", required = true, example = "张三")
private string username;
@apimodelproperty(value = "邮箱", example = "zhangsan@example.com")
private string email;
// 构造方法、getter/setter 省略
}- @api:用在 controller 类上,对接口分组。
- @apioperation:描述接口方法。
- @apiparam:描述参数。
- @apimodel 和 @apimodelproperty:描述实体和字段,会在 schema 中展示。
刷新 swagger 页面,你会看到“用户管理”标签下的两个接口,并且可以点击 try it out 进行调试。
五、高级配置:分组与多环境
当接口数量增多时,可以通过分组进行管理。例如将用户模块和订单模块分开:
@bean
public docket userapi() {
return new docket(documentationtype.oas_30)
.groupname("用户模块")
.apiinfo(apiinfo())
.select()
.apis(requesthandlerselectors.basepackage("com.example.demo.controller.user"))
.paths(pathselectors.any())
.build();
}
@bean
public docket orderapi() {
return new docket(documentationtype.oas_30)
.groupname("订单模块")
.apiinfo(apiinfo())
.select()
.apis(requesthandlerselectors.basepackage("com.example.demo.controller.order"))
.paths(pathselectors.any())
.build();
}在 swagger ui 页面右上角可以选择不同的 group。
对于多环境(开发/测试/生产),swagger 文档通常只在开发环境暴露。可以通过 @profile 或 @conditionalonproperty 控制:
@configuration
@profile({"dev", "test"})
public class swaggerconfig {
// 配置内容不变
}这样在生产环境就不会加载 swagger 配置,避免接口暴露。
六、spring boot 3.x 适配方案
如果你使用 spring boot 3.x(基于 jakarta ee),springfox 已不再维护,推荐使用 springdoc-openapi:
<dependency>
<groupid>org.springdoc</groupid>
<artifactid>springdoc-openapi-starter-webmvc-ui</artifactid>
<version>2.1.0</version>
</dependency>配置类只需少量调整:
import io.swagger.v3.oas.models.openapi;
import io.swagger.v3.oas.models.info.info;
import org.springframework.context.annotation.bean;
import org.springframework.context.annotation.configuration;
@configuration
public class openapiconfig {
@bean
public openapi customopenapi() {
return new openapi()
.info(new info()
.title("用户管理 api")
.version("1.0.0")
.description("spring boot 3.x 集成 swagger 示例"));
}
}访问地址与 springfox 一致。注解方面,springdoc 支持 swagger 2 注解和 openapi 3 注解,过渡平滑。
七、常见问题与避坑指南
- 404 页面打不开? 检查是否存在静态资源拦截,确保
/swagger-ui/**不被拦截。 - 接口列表为空? 确认
basepackage路径是否正确,controller 是否被 spring 管理。 - 参数或实体描述不显示? 检查是否在实体类上使用了 lombok 的
@data但没有显式写 getter/setter,某些版本可能无法解析。 - 生产环境一定不要暴露 swagger! 使用
@profile或配置开关严格控制。
八、总结
本文从 swagger 的作用讲起,涵盖了 spring boot 2.x 和 3.x 的集成方式,通过丰富的代码示例演示了核心注解、分组配置以及环境隔离。掌握 swagger 后,你可以让接口文档随着代码自动更新,彻底告别文档与代码不一致的烦恼。接下来,不妨在项目中尝试一下,并根据团队习惯选择 springfox 或 springdoc-openapi。
到此这篇关于swagger从入门到集成实战指南,打造丝滑的 api 文档的文章就介绍到这了,更多相关swagger入门到实战内容请搜索代码网以前的文章或继续浏览下面的相关文章希望大家以后多多支持代码网!
发表评论