引言:为什么需要Swagger UI
在现代软件开发中,API(应用程序编程接口)是连接前后端以及不同服务之间的桥梁。随着微服务架构的流行,API的数量急剧增加,如何高效地管理、测试和文档化这些API成为了开发团队面临的重要挑战。Swagger(现称为OpenAPI)正是为了解决这一问题而生的工具集,它能够自动生成API文档,并提供交互式的测试界面。
Spring Boot作为Java生态中最流行的微服务框架,与Swagger的集成已经成为行业标准实践。通过Swagger UI,开发者可以:
实时查看API文档
:无需编写额外的文档,自动生成符合OpenAPI规范的文档
在线调试API
:直接在浏览器中测试API,无需使用Postman等第三方工具
降低沟通成本
:前端和后端开发者可以通过同一份文档进行协作
支持版本管理
:不同版本的API可以有不同的文档
本文将从零开始,详细介绍如何在Spring Boot项目中集成Swagger UI,涵盖基础配置、高级定制以及常见问题的排查方法。
一、基础环境准备
1.1 创建Spring Boot项目
首先,我们需要创建一个基础的Spring Boot项目。可以通过以下几种方式:
方式一:使用Spring Initializr(推荐)
访问
start.spring.io
,选择以下配置:
Project: Maven Project
Language: Java
Spring Boot: 3.x.x(推荐最新稳定版)
Group: com.example
Artifact: swagger-demo
Dependencies: Spring Web
方式二:使用IDE创建
在IntelliJ IDEA或Eclipse中,选择File → New → Project → Spring Initializr,然后进行相同配置。
方式三:手动创建pom.xml
如果已有项目,确保pom.xml中包含基础依赖:
在pom.xml中添加Swagger相关依赖。根据Spring Boot版本选择合适的Swagger版本:
对于Spring Boot 2.x:
对于Spring Boot 3.x(推荐):
由于Spring Boot 3.x基于Spring Framework 6,需要使用SpringDoc(OpenAPI 3)替代传统的Swagger:
注意
:本文以Spring Boot 3.x和SpringDoc为例进行讲解,这是目前最主流和推荐的方案。
1.3 创建基础Controller
为了演示Swagger效果,我们先创建一个简单的REST Controller:
package com.example.swaggerdemo.controller;
import org.springframework.web.bind.annotation.*;
@RestController
@RequestMapping(“/api/users”)
public class UserController {
@GetMapping(“/{id}”)
public String getUserById(@PathVariable Long id) {
return “User ” + id;
}
@PostMapping
public String createUser(@RequestBody String user) {
return “Created user: ” + user;
}
}
二、基础配置:从零开始集成Swagger UI
2.1 创建Swagger配置类
在Spring Boot 3.x中,我们可以通过配置类或配置文件来定制Swagger。首先创建一个配置类:
package com.example.swaggerdemo.config;
import io.swagger.v3.oas.models.OpenAPI;
import io.swagger.v3.oas.models.info.Contact;
import io.swagger.v3.oas.models.info.Info;
import io.swagger.v3.oas.models.info.License;
import org.springdoc.core.models.GroupedOpenApi;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
public class SwaggerConfig {
/**
* 基础OpenAPI配置
* 定义API的基本信息,包括标题、描述、版本、联系人等
*/
@Bean
public OpenAPI customOpenAPI() {
return new OpenAPI()
.info(new Info()
.title(“用户管理API文档”)
.description(“提供用户信息的增删改查接口文档”)
.version(“1.0.0”)
.contact(new Contact()
.name(“开发团队”)
.email(“dev@example.com”)
.url(“https://example.com”))
.license(new License()
.name(“Apache 2.0”)
.url(“http://springdoc.org”)));
}
/**
* 分组API配置
* 可以创建多个分组,用于管理不同模块的API
*/
@Bean
public GroupedOpenApi publicApi() {
return GroupedOpenApi.builder()
.group(“public”)
.pathsToMatch(“/api/**”)
.build();
}
/**
* 内部API分组(可选)
*/
@Bean
public GroupedOpenApi internalApi() {
return GroupedOpenApi.builder()
.group(“internal”)
.pathsToMatch(“/internal/**”)
.build();
}
}
2.2 配置application.properties
在
src/main/resources/application.properties
中添加Swagger相关配置:
# SpringDoc配置
springdoc.api-docs.path=/api-docs
springdoc.swagger-ui.path=/swagger-ui.html
springdoc.swagger-ui.operations-sorter=method
springdoc.swagger-ui.tags-sorter=alpha
springdoc.swagger-ui.doc-expansion=none
springdoc.swagger-ui.default-model-rendering=model
springdoc.swagger-ui.display-request-duration=true
springdoc.swagger-ui.filter=true
springdoc.swagger-ui.show-extensions=true
springdoc.swagger-ui.show-common-extensions=true
# 安全配置(可选,生产环境建议关闭)
springdoc.swagger-ui.enabled=true
springdoc.api-docs.enabled=true
# 如果需要在生产环境关闭,可以设置:
# springdoc.swagger-ui.enabled=false
# springdoc.api-docs.enabled=false
2.3 添加Swagger注解到Controller
现在,为Controller添加Swagger注解,使文档更加详细:
package com.example.swaggerdemo.controller;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.media.Content;
import io.swagger.v3.oas.annotations.media.Schema;
import io.swagger.v3.oas.annotations.responses.ApiResponse;
import io.swagger.v3.oas.annotations.responses.ApiResponses;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.springframework.web.bind.annotation.*;
@RestController
@RequestMapping(“/api/users”)
@Tag(name = “用户管理”, description = “用户信息的增删改查接口”)
public class UserController {
@Operation(
summary = “根据ID获取用户”,
description = “根据用户ID查询用户详细信息,返回用户对象的JSON表示”
)
@ApiResponses(value = {
@ApiResponse(
responseCode = “200”,
description = “成功找到用户”,
content = @Content(mediaType = “application/json”,
schema = @Schema(implementation = User.class))
),
@ApiResponse(
responseCode = “404”,
description = “用户未找到”
)
})
@GetMapping(“/{id}”)
public User getUserById(
@Parameter(description = “用户ID”, required = true, example = “1”)
@PathVariable Long id) {
// 模拟返回用户对象
return new User(id, “张三”, “zhangsan@example.com”);
}
@Operation(
summary = “创建新用户”,
description = “根据提供的用户信息创建新用户”
)
@ApiResponses(value = {
@ApiResponse(
responseCode = “200”,
description = “用户创建成功”
),
@ApiResponse(
responseCode = “400”,
description = “无效的输入数据”
)
})
@PostMapping
public User createUser(
@Parameter(description = “用户对象”, required = true)
@RequestBody User user) {
// 模拟创建用户
user.setId(1L); // 模拟生成ID
return user;
}
@Operation(
summary = “更新用户信息”,
description = “根据ID更新指定用户的详细信息”
)
@PutMapping(“/{id}”)
public User updateUser(
@Parameter(description = “用户ID”, required = true)
@PathVariable Long id,
@Parameter(description = “更新的用户信息”, required = true)
@RequestBody User user) {
user.setId(id);
return user;
}
@Operation(
summary = “删除用户”,
description = “根据ID删除指定用户”
)
@DeleteMapping(“/{id}”)
public String deleteUser(
@Parameter(description = “用户ID”, required = true)
@PathVariable Long id) {
return “用户 ” + id + ” 已删除”;
}
}
// 用户模型类
class User {
@Schema(description = “用户ID”, example = “1”)
private Long id;
@Schema(description = “用户名”, example = “张三”, required = true)
private String name;
@Schema(description = “邮箱”, example = “zhangsan@example.com”, required = true)
private String email;
// 构造函数
public User() {}
public User(Long id, String name, String email) {
this.id = id;
this.name = name;
this.email = email;
}
// Getter和Setter
public Long getId() { return id; }
public void setId(Long id) { this.id = id; }
public String getName() { return name; }
public void setName(String name) { this.name = name; }
public String getEmail() { return email; }
public void setEmail(String email) { this.email = email; }
}
2.4 启动应用并验证
现在可以启动Spring Boot应用了:
mvn spring-boot:run
启动后访问:
Swagger UI界面
:
http://localhost:8080/swagger-ui.html
API文档JSON
:
http://localhost:8080/api-docs
你应该能看到一个交互式的API文档界面,可以展开每个接口查看详细信息,并直接进行测试。
三、高级定制:打造企业级API文档
3.1 自定义Swagger UI界面
3.1.1 修改Swagger UI主题和布局
通过配置类可以深度定制Swagger UI的外观和行为:
package com.example.swaggerdemo.config;
import org.springdoc.core.models.GroupedOpenApi;
import org.springdoc.core.properties.SwaggerUiConfigProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import java.util.HashMap;
import java.util.Map;
@Configuration
public class SwaggerAdvancedConfig {
/**
* 高级UI配置
*/
@Bean
public SwaggerUiConfigProperties swaggerUiConfig() {
SwaggerUiConfigProperties config = new SwaggerUiConfigProperties();
// 基础配置
config.setPath(“/swagger-ui.html”);
config.setDocExpansion(“none”); // 折叠所有文档
config.setOperationsSorter(“method”); // 按方法排序
config.setTagsSorter(“alpha”); // 按字母顺序排序标签
config.setDefaultModelRendering(“model”); // 显示模型
config.setDisplayRequestDuration(true); // 显示请求耗时
config.setFilter(true); // 启用过滤器
config.setShowExtensions(true); // 显示扩展信息
config.setShowCommonExtensions(true); // 显示公共扩展
// 自定义CSS(可选)
Map
customCss.put(“customCss”, “.swagger-ui .topbar { background-color: #2c3e50; }”);
config.setCustomCss(customCss);
return config;
}
/**
* 多分组API配置
* 适用于大型项目,不同模块的API分开管理
*/
@Bean
public GroupedOpenApi userApi() {
return GroupedOpenApi.builder()
.group(“用户模块”)
.pathsToMatch(“/api/users/**”)
.build();
}
@Bean
public GroupedOpenApi orderApi() {
return GroupedOpenApi.builder()
.group(“订单模块”)
.pathsToMatch(“/api/orders/**”)
.build();
}
@Bean
public GroupedOpenApi productApi() {
return GroupedOpenApi.builder()
.group(“商品模块”)
.pathsToMatch(“/api/products/**”)
.build();
}
}
3.1.2 自定义静态资源(高级)
如果需要更深度的定制,可以替换Swagger UI的静态资源:
在
src/main/resources/static
目录下创建
swagger-custom.html
:
在配置中指定自定义路径:
springdoc.swagger-ui.path=/custom-docs.html
3.2 深度注解配置
3.2.1 完整的Controller示例
package com.example.swaggerdemo.controller;
import io.swagger.v3.oas.annotations.*;
import io.swagger.v3.oas.annotations.media.*;
import io.swagger.v3.oas.annotations.responses.ApiResponse;
import io.swagger.v3.oas.annotations.responses.ApiResponses;
import io.swagger.v3.oas.annotations.security.SecurityRequirement;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import java.util.Arrays;
import java.util.List;
@RestController
@RequestMapping(“/api/v1/users”)
@Tag(name = “用户管理”, description = “用户CRUD操作接口”)
@SecurityRequirement(name = “bearerAuth”) // 安全认证
public class AdvancedUserController {
@Operation(
summary = “分页查询用户列表”,
description = “支持分页、排序和条件查询的用户列表接口”,
operationId = “listUsers”,
responses = {
@ApiResponse(
responseCode = “200”,
description = “成功获取用户列表”,
content = @Content(
mediaType = “application/json”,
array = @ArraySchema(schema = @Schema(implementation = UserResponse.class))
)
),
@ApiResponse(
responseCode = “400”,
description = “请求参数无效”,
content = @Content(schema = @Schema(implementation = ErrorResponse.class))
)
}
)
@GetMapping
public ResponseEntity> listUsers(
@Parameter(description = “页码,从1开始”, example = “1”)
@RequestParam(defaultValue = “1”) Integer page,
@Parameter(description = “每页大小”, example = “10”)
@RequestParam(defaultValue = “10”) Integer size,
@Parameter(description = “排序字段”, example = “name”)
@RequestParam(required = false) String sortBy,
@Parameter(description = “用户状态”, schema = @Schema(allowableValues = {“ACTIVE”, “INACTIVE”, “ALL”}))
@RequestParam(defaultValue = “ACTIVE”) String status) {
// 模拟数据
List
new UserResponse(1L, “张三”, “zhangsan@example.com”, “ACTIVE”),
new UserResponse(2L, “李四”, “lisi@example.com”, “ACTIVE”)
);
return ResponseEntity.ok(users);
}
@Operation(
summary = “批量创建用户”,
description = “一次性创建多个用户,提高批量操作效率”,
requestBody = @RequestBody(
description = “用户列表”,
required = true,
content = @Content(
mediaType = “application/json”,
array = @ArraySchema(schema = @Schema(implementation = UserRequest.class))
)
)
)
@PostMapping(“/batch”)
public ResponseEntity
@RequestBody List
return ResponseEntity.ok(“成功创建 ” + users.size() + ” 个用户”);
}
@Operation(
summary = “部分更新用户”,
description = “使用JSON Patch格式部分更新用户字段”,
requestBody = @RequestBody(
description = “JSON Patch文档”,
required = true,
content = @Content(
mediaType = “application/json”,
schema = @Schema(implementation = JsonPatch.class)
)
)
)
@PatchMapping(“/{id}”)
public ResponseEntity
@Parameter(description = “用户ID”, required = true)
@PathVariable Long id,
@RequestBody Object patch) {
// 实现部分更新逻辑
UserResponse user = new UserResponse(id, “张三”, “zhangsan@example.com”, “ACTIVE”);
return ResponseEntity.ok(user);
}
}
// 请求模型
@Schema(description = “用户创建请求”)
class UserRequest {
@Schema(description = “用户名”, required = true, example = “王五”)
private String name;
@Schema(description = “邮箱”, required = true, example = “wangwu@example.com”)
private String email;
@Schema(description = “手机号”, example = “13800138000”)
private String phone;
// Getter和Setter
public String getName() { return name; }
public void setName(String name) { this.name = name; }
public String getEmail() { return email; }
public void setEmail(String email) { this.email = email; }
public String getPhone() { return phone; }
public void setPhone(String phone) { this.phone = phone; }
}
// 响应模型
@Schema(description = “用户响应”)
class UserResponse {
@Schema(description = “用户ID”, example = “1”)
private Long id;
@Schema(description = “用户名”, example = “张三”)
private String name;
@Schema(description = “邮箱”, example = “zhangsan@example.com”)
private String email;
@Schema(description = “状态”, example = “ACTIVE”, allowableValues = {“ACTIVE”, “INACTIVE”})
private String status;
public UserResponse() {}
public UserResponse(Long id, String name, String email, String status) {
this.id = id;
this.name = name;
this.email = email;
this.status = status;
}
// Getter和Setter
public Long getId() { return id; }
public void setId(Long id) { this.id = id; }
public String getName() { return name; }
public void setName(String name) { this.name = name; }
public String getEmail() { return email; }
public void setEmail(String email) { this.email = email; }
public String getStatus() { return status; }
public void setStatus(String status) { this.status = status; }
}
// 错误响应模型
@Schema(description = “错误响应”)
class ErrorResponse {
@Schema(description = “错误码”, example = “USER_NOT_FOUND”)
private String code;
@Schema(description = “错误信息”, example = “用户不存在”)
private String message;
// Getter和Setter
public String getCode() { return code; }
public void setCode(String code) { this.code = code; }
public String getMessage() { return message; }
public void setMessage(String message) { this.message = message; }
}
// JSON Patch模型(简化)
@Schema(description = “JSON Patch操作”)
class JsonPatch {
@Schema(description = “操作类型”, example = “replace”, allowableValues = {“add”, “remove”, “replace”, “move”, “copy”, “test”})
private String op;
@Schema(description = “路径”, example = “/name”)
private String path;
@Schema(description = “值”)
private Object value;
// Getter和Setter
public String getOp() { return op; }
public void setOp(String op) { this.op = op; }
public String getPath() { return path; }
public void setPath(String path) { this.path = path; }
public Object getValue() { return value; }
public void setValue(Object value) { this.value = value; }
}
3.3 安全认证集成
3.3.1 JWT认证集成
在实际项目中,API通常需要认证。以下是集成JWT认证的Swagger配置:
package com.example.swaggerdemo.config;
import io.swagger.v3.oas.models.Components;
import io.swagger.v3.oas.models.OpenAPI;
import io.swagger.v3.oas.models.info.Info;
import io.swagger.v3.oas.models.security.SecurityRequirement;
import io.swagger.v3.oas.models.security.SecurityScheme;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
public class SecuritySwaggerConfig {
@Bean
public OpenAPI customOpenAPI() {
return new OpenAPI()
.info(new Info()
.title(“安全API文档”)
.version(“1.0.0”)
.description(“需要JWT认证的API文档”))
.addSecurityItem(new SecurityRequirement().addList(“bearerAuth”))
.components(new Components()
.addSecuritySchemes(“bearerAuth”, new SecurityScheme()
.type(SecurityScheme.Type.HTTP)
.scheme(“bearer”)
.bearerFormat(“JWT”)
.in(SecurityScheme.In.HEADER)
.name(“Authorization”)));
}
}
在Controller中使用安全注解:
@RestController
@RequestMapping(“/api/secure”)
@Tag(name = “安全接口”, description = “需要认证的接口”)
@SecurityRequirement(name = “bearerAuth”)
public class SecureController {
@Operation(
summary = “获取敏感数据”,
description = “需要JWT认证才能访问的接口”
)
@GetMapping(“/data”)
public String getSecureData() {
return “这是受保护的数据”;
}
}
3.4 多环境配置
3.4.1 使用Profile控制Swagger启用
在生产环境中,通常需要关闭Swagger。可以通过Profile实现:
package com.example.swaggerdemo.config;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Profile;
import org.springdoc.core.models.GroupedOpenApi;
@Configuration
public class ProfileConfig {
// 开发环境启用
@Bean
@Profile({“dev”, “local”})
public GroupedOpenApi devApi() {
return GroupedOpenApi.builder()
.group(“development”)
.pathsToMatch(“/api/**”)
.build();
}
// 测试环境启用
@Bean
@Profile({“test”})
public GroupedOpenApi testApi() {
return GroupedOpenApi.builder()
.group(“test”)
.pathsToMatch(“/api/**”)
.build();
}
}
在
application-dev.properties
中:
springdoc.swagger-ui.enabled=true
springdoc.api-docs.enabled=true
在
application-prod.properties
中:
springdoc.swagger-ui.enabled=false
springdoc.api-docs.enabled=false
3.5 自定义文档分组
对于大型项目,可以按业务模块分组:
@Bean
public GroupedOpenApi orderApi() {
return GroupedOpenApi.builder()
.group(“订单管理”)
.pathsToMatch(“/api/orders/**”)
.addOpenApiCustomizer(openApi -> {
openApi.getInfo().setTitle(“订单管理API”);
openApi.getInfo().setDescription(“订单相关接口文档”);
})
.build();
}
@Bean
public GroupedOpenApi paymentApi() {
return GroupedOpenApi.builder()
.group(“支付管理”)
.pathsToMatch(“/api/payments/**”)
.addOpenApiCustomizer(openApi -> {
openApi.getInfo().setTitle(“支付管理API”);
openApi.getInfo().setDescription(“支付相关接口文档”);
})
.build();
}
四、Spring Boot 2.x与3.x的差异说明
4.1 依赖差异
Spring Boot 2.x(使用Springfox):
Spring Boot 3.x(使用SpringDoc):
4.2 配置类差异
Spring Boot 2.x配置:
@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文档”)
.version(“1.0”)
.build();
}
}
Spring Boot 3.x配置:
@Configuration
public class SwaggerConfig {
@Bean
public OpenAPI customOpenAPI() {
return new OpenAPI()
.info(new Info()
.title(“API文档”)
.version(“1.0.0”));
}
}
4.3 注解差异
Spring Boot 2.x注解:
@Api
@ApiOperation
@ApiParam
@ApiModel
@ApiModelProperty
Spring Boot 3.x注解:
@Tag
@Operation
@Parameter
@Schema
@ApiResponse
五、常见问题排查
5.1 Swagger UI无法访问
问题描述
:访问
http://localhost:8080/swagger-ui.html显示404错误。
解决方案
:
检查依赖是否正确
:
mvn dependency:tree | grep springdoc
确保有
springdoc-openapi-starter-webmvc-ui
依赖。
检查配置
:
# 确保路径正确
springdoc.swagger-ui.path=/swagger-ui.html
springdoc.api-docs.path=/api-docs
检查Controller扫描
:
确保Controller在主应用类的同级或子包中:
@SpringBootApplication
@ComponentScan(basePackages = “com.example”)
public class SwaggerDemoApplication {
public static void main(String[] args) {
SpringApplication.run(SwaggerDemoApplication.class, args);
}
}
检查端口和上下文路径
:
server.port=8080
server.servlet.context-path=/api
# 访问时需要:http://localhost:8080/api/swagger-ui.html
5.2 文档不显示Controller
问题描述
:Swagger UI加载成功,但没有Controller的接口文档。
解决方案
:
检查注解
:
确保Controller类有
@RestController
或
@Controller
注解。
检查路径匹配
:
在配置类中检查
pathsToMatch
:
GroupedOpenApi.builder()
.pathsToMatch(“/api/**”, “/internal/**”) // 确保匹配你的路径
.build();
排除静态资源
:
如果Controller返回静态资源,可能被过滤:
@Bean
public GroupedOpenApi publicApi() {
return GroupedOpenApi.builder()
.group(“public”)
.pathsToMatch(“/api/**”)
.pathsToExclude(“/api/static/**”)
.build();
}
5.3 模型类不显示
问题描述
:接口文档中没有显示请求/响应模型的详细字段。
解决方案
:
添加Schema注解
:
@Schema(description = “用户模型”)
public class User {
@Schema(description = “用户ID”, example = “1”)
private Long id;
@Schema(description = “用户名”, required = true)
private String name;
}
确保有Getter方法
:
Swagger只读取Getter方法,不读取字段本身。
检查包扫描
:
模型类应该在Controller所在的包或子包中。
5.4 生产环境安全问题
问题描述
:生产环境暴露了Swagger接口,存在安全风险。
解决方案
:
使用Profile控制
:
@Bean
@Profile(“!prod”)
public OpenAPI customOpenAPI() {
return new OpenAPI()
.info(new Info()
.title(“API文档”)
.version(“1.0.0”));
}
使用Spring Security限制访问
:
@Configuration
@EnableWebSecurity
public class SecurityConfig {
@Bean
public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
http
.authorizeHttpRequests(auth -> auth
.requestMatchers(“/swagger-ui.html”, “/api-docs/**”).hasRole(“ADMIN”)
.anyRequest().authenticated()
);
return http.build();
}
}
配置文件控制
:
# application-prod.properties
springdoc.swagger-ui.enabled=false
springdoc.api-docs.enabled=false
5.5 版本兼容性问题
问题描述
:升级Spring Boot后Swagger无法工作。
解决方案
:
Spring Boot 2.7+ 升级到 3.x
:
必须将
springfox
替换为
springdoc
更新所有注解(@Api → @Tag等)
Java版本至少需要17
检查依赖冲突
:
mvn dependency:tree
排除冲突的
swagger-models
或
jackson
版本。
使用兼容版本
:
5.6 性能优化
问题描述
:Swagger加载缓慢,影响开发体验。
解决方案
:
限制文档大小
:
springdoc.api-docs.resolve-schema-properties=true
springdoc.swagger-ui.default-model-rendering=simple
使用缓存
:
@Bean
public OpenAPI customOpenAPI() {
// 缓存OpenAPI对象
return new OpenAPI()
.info(new Info()
.title(“API文档”)
.version(“1.0.0”));
}
分组加载
:
只加载需要的API分组,避免一次性加载所有接口。
5.7 自定义验证错误显示
问题描述
:使用
@Valid
注解时,Swagger不显示验证规则。
解决方案
:
@RestController
@RequestMapping(“/api/validate”)
public class ValidationController {
@PostMapping(“/user”)
public User createUser(
@Valid @RequestBody User user) {
return user;
}
}
@Schema(description = “用户模型”)
class User {
@Schema(description = “用户名”, example = “张三”, required = true)
@NotBlank(message = “用户名不能为空”)
private String name;
@Schema(description = “邮箱”, example = “user@example.com”, required = true)
@Email(message = “邮箱格式不正确”)
private String email;
@Schema(description = “年龄”, example = “18”, minimum = “0”, maximum = “150”)
@Min(0) @Max(150)
private Integer age;
// Getter和Setter
}
5.8 多模块项目配置
问题描述
:多模块Maven项目中Swagger无法扫描到其他模块的Controller。
解决方案
:
主模块配置
:
@SpringBootApplication
@ComponentScan(basePackages = {“com.example.module1”, “com.example.module2”})
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}
每个模块独立配置
:
在每个模块的
application.properties
中:
springdoc.swagger-ui.path=/module1/swagger-ui.html
springdoc.api-docs.path=/module1/api-docs
使用网关统一文档
:
如果使用Spring Cloud Gateway,可以在网关层聚合所有服务的Swagger文档。
5.9 常见错误代码及含义
错误现象
可能原因
解决方案
404 Not Found
路径配置错误
检查
springdoc.swagger-ui.path
500 Internal Error
注解使用错误
检查@Schema等注解参数
文档为空
包扫描问题
检查@ComponentScan或@ServletComponentScan
模型不显示
缺少Getter
确保模型类有Getter/Setter
样式错乱
缓存问题
清除浏览器缓存或Ctrl+F5强制刷新
5.10 调试技巧
查看OpenAPI JSON
:
访问
http://localhost:8080/api-docs
查看原始JSON,检查结构是否正确。
使用Swagger Validator
:
在Swagger UI中点击”Validate”按钮,检查文档是否符合OpenAPI规范。
日志调试
:
logging.level.org.springdoc=DEBUG
logging.level.io.swagger.v3=DEBUG
浏览器开发者工具
:
检查Network标签页,确认
api-docs
和
swagger-ui
资源是否成功加载。
六、最佳实践建议
6.1 文档规范
统一命名规范
:
接口路径使用小写和连字符:
/api/user-list
模型类名使用大驼峰:
UserResponse
字段名使用小驼峰:
userName
详细的描述
:
每个接口都要有summary和description
每个参数都要有description和example
每个模型字段都要有description和example
版本管理
:
@Tag(name = “用户管理”, description = “v1版本用户接口”)
@RequestMapping(“/api/v1/users”)
6.2 安全建议
生产环境必须关闭
:
springdoc.swagger-ui.enabled=false
springdoc.api-docs.enabled=false
访问控制
:
使用Spring Security限制访问
只允许内网或VPN访问
使用IP白名单
敏感信息脱敏
:
@Schema(description = “密码”, accessMode = Schema.AccessMode.WRITE_ONLY)
private String password;
6.3 性能建议
按需加载
:
使用分组API,避免一次性加载所有接口
只在开发环境启用
缓存策略
:
OpenAPI对象可以缓存
避免重复解析注解
异步加载
:
对于大型API,考虑异步加载文档
6.4 团队协作
文档即代码
:
将Swagger注解纳入代码审查
使用CI/CD自动验证文档完整性
API设计先行
:
先设计Swagger文档,再实现代码
使用Swagger Codegen生成代码骨架
文档同步
:
确保代码和文档同步更新
使用自动化测试验证文档准确性
七、总结
本文详细介绍了Spring Boot集成Swagger UI的完整流程,从基础配置到高级定制,再到常见问题排查。关键要点总结:
基础集成
:Spring Boot 3.x推荐使用SpringDoc,依赖简单,配置灵活
高级定制
:通过配置类可以实现多分组、安全认证、自定义UI等高级功能
注解使用
:掌握@Tag、@Operation、@Parameter、@Schema等核心注解
问题排查
:常见问题都有明确的解决方案,关键是检查依赖、配置和注解
最佳实践
:生产环境必须关闭,开发环境规范使用,注重安全和性能
通过本文的指导,你应该能够在Spring Boot项目中成功集成Swagger UI,并根据项目需求进行深度定制。记住,好的API文档是团队协作的基石,也是高质量软件的重要标志。