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

Spring Boot 集成 Swagger UI 详细教程

1. 什么是Swagger?

Swagger是一个用于设计、构建、记录和使用RESTful Web服务的开源软件框架。Swagger UI提供了一个可视化的界面,让你能够:

  • 查看API文档
  • 在线测试API接口
  • 自动生成接口文档

2. 环境准备

2.1 必要工具

  • JDK 8 或更高版本
  • Maven 3.6+ 或 Gradle 6+
  • IDE(IntelliJ IDEA、Eclipse等)

2.2 Spring Boot版本说明

  • Spring Boot 2.x 使用 Springfox
  • Spring Boot 3.x 使用 Springdoc OpenAPI

3. 方案一:Spring Boot 2.x + Springfox(推荐新手)

3.1 创建Spring Boot项目

使用Spring Initializr创建项目

访问 https://start.spring.io/ 或使用IDE创建项目,选择以下依赖:

  • Spring Web
  • Spring Boot DevTools(可选)
或使用Maven命令创建
mvn archetype:generate -DgroupId=com.example -DartifactId=swagger-demo \-DarchetypeArtifactId=maven-archetype-quickstart -DinteractiveMode=false

3.2 添加Maven依赖

pom.xml 文件中添加以下依赖:

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"><modelVersion>4.0.0</modelVersion><parent><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-parent</artifactId><version>2.7.14</version><relativePath/></parent><groupId>com.example</groupId><artifactId>swagger-demo</artifactId><version>1.0.0</version><name>swagger-demo</name><description>Spring Boot Swagger Demo</description><properties><java.version>8</java.version></properties><dependencies><!-- Spring Boot Web Starter --><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-web</artifactId></dependency><!-- Swagger UI --><dependency><groupId>io.springfox</groupId><artifactId>springfox-swagger-ui</artifactId><version>3.0.0</version></dependency><!-- Swagger 2 --><dependency><groupId>io.springfox</groupId><artifactId>springfox-swagger2</artifactId><version>3.0.0</version></dependency><!-- Spring Boot Starter Test --><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-test</artifactId><scope>test</scope></dependency></dependencies><build><plugins><plugin><groupId>org.springframework.boot</groupId><artifactId>spring-boot-maven-plugin</artifactId></plugin></plugins></build>
</project>

3.3 创建Swagger配置类

创建 src/main/java/com/example/config/SwaggerConfig.java

package com.example.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;
import springfox.documentation.swagger2.annotations.EnableSwagger2;@Configuration
@EnableSwagger2
public class SwaggerConfig {/*** 创建API文档*/@Beanpublic Docket createRestApi() {return new Docket(DocumentationType.SWAGGER_2)// API基本信息.apiInfo(apiInfo())// 选择那些路径和api会生成document.select()// 对所有api进行监控.apis(RequestHandlerSelectors.basePackage("com.example.controller"))// 对所有路径进行监控.paths(PathSelectors.any()).build();}/*** API信息*/private ApiInfo apiInfo() {return new ApiInfoBuilder().title("Spring Boot Swagger Demo API文档").description("这是一个Spring Boot集成Swagger的示例项目").contact(new Contact("开发者", "https://example.com", "developer@example.com")).version("1.0.0").build();}
}

3.4 创建实体类

创建 src/main/java/com/example/entity/User.java

package com.example.entity;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 = "用户名", example = "张三", required = true)private String username;@ApiModelProperty(value = "邮箱", example = "zhangsan@example.com")private String email;@ApiModelProperty(value = "年龄", example = "25")private Integer age;// 无参构造函数public User() {}// 有参构造函数public User(Long id, String username, String email, Integer age) {this.id = id;this.username = username;this.email = email;this.age = age;}// Getter和Setter方法public Long getId() {return id;}public void setId(Long id) {this.id = id;}public String getUsername() {return username;}public void setUsername(String username) {this.username = username;}public String getEmail() {return email;}public void setEmail(String email) {this.email = email;}public Integer getAge() {return age;}public void setAge(Integer age) {this.age = age;}
}

3.5 创建Controller

创建 src/main/java/com/example/controller/UserController.java

package com.example.controller;import com.example.entity.User;
import io.swagger.annotations.*;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;import java.util.ArrayList;
import java.util.List;@RestController
@RequestMapping("/api/users")
@Api(tags = "用户管理", description = "用户相关的API")
public class UserController {// 模拟数据库private List<User> users = new ArrayList<>();private Long idCounter = 1L;// 初始化一些数据{users.add(new User(idCounter++, "张三", "zhangsan@example.com", 25));users.add(new User(idCounter++, "李四", "lisi@example.com", 30));}@ApiOperation(value = "获取所有用户", notes = "返回系统中的所有用户列表")@ApiResponses({@ApiResponse(code = 200, message = "成功获取用户列表"),@ApiResponse(code = 500, message = "服务器内部错误")})@GetMappingpublic List<User> getAllUsers() {return users;}@ApiOperation(value = "根据ID获取用户", notes = "根据用户ID获取特定用户信息")@ApiImplicitParam(name = "id", value = "用户ID", required = true, dataType = "Long", paramType = "path", example = "1")@GetMapping("/{id}")public ResponseEntity<User> getUserById(@PathVariable Long id) {User user = users.stream().filter(u -> u.getId().equals(id)).findFirst().orElse(null);if (user != null) {return ResponseEntity.ok(user);} else {return ResponseEntity.notFound().build();}}@ApiOperation(value = "创建新用户", notes = "在系统中创建一个新的用户")@ApiImplicitParam(name = "user", value = "用户信息", required = true, dataType = "User")@PostMappingpublic User createUser(@RequestBody User user) {user.setId(idCounter++);users.add(user);return user;}@ApiOperation(value = "更新用户信息", notes = "更新指定ID的用户信息")@ApiImplicitParams({@ApiImplicitParam(name = "id", value = "用户ID", required = true, dataType = "Long", paramType = "path"),@ApiImplicitParam(name = "user", value = "更新的用户信息", required = true, dataType = "User")})@PutMapping("/{id}")public ResponseEntity<User> updateUser(@PathVariable Long id, @RequestBody User updatedUser) {for (int i = 0; i < users.size(); i++) {User user = users.get(i);if (user.getId().equals(id)) {updatedUser.setId(id);users.set(i, updatedUser);return ResponseEntity.ok(updatedUser);}}return ResponseEntity.notFound().build();}@ApiOperation(value = "删除用户", notes = "根据用户ID删除用户")@ApiImplicitParam(name = "id", value = "用户ID", required = true, dataType = "Long", paramType = "path")@DeleteMapping("/{id}")public ResponseEntity<Void> deleteUser(@PathVariable Long id) {boolean removed = users.removeIf(user -> user.getId().equals(id));if (removed) {return ResponseEntity.ok().build();} else {return ResponseEntity.notFound().build();}}
}

3.6 创建启动类

创建 src/main/java/com/example/SwaggerDemoApplication.java

package com.example;import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;@SpringBootApplication
public class SwaggerDemoApplication {public static void main(String[] args) {SpringApplication.run(SwaggerDemoApplication.class, args);System.out.println("应用启动成功!");System.out.println("Swagger UI访问地址: http://localhost:8080/swagger-ui.html");}
}

3.7 配置文件

创建 src/main/resources/application.properties

# 应用名称
spring.application.name=swagger-demo# 服务器端口
server.port=8080# 日志配置
logging.level.root=INFO
logging.level.com.example=DEBUG# Swagger配置(可选)
# 禁用swagger,生产环境建议设置为true
swagger.enabled=true

3.8 运行项目

方法1:使用IDE运行
  1. 在IDE中右键点击 SwaggerDemoApplication.java
  2. 选择 "Run SwaggerDemoApplication"
方法2:使用Maven命令运行
# 编译项目
mvn clean compile# 运行项目
mvn spring-boot:run
方法3:打包运行
# 打包
mvn clean package# 运行jar包
java -jar target/swagger-demo-1.0.0.jar

3.9 访问Swagger UI

启动成功后,在浏览器中访问:

http://localhost:8080/swagger-ui.html

你会看到一个漂亮的API文档界面!

4. 方案二:Spring Boot 3.x + Springdoc OpenAPI(推荐)

4.1 Maven依赖(Spring Boot 3.x)

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"><modelVersion>4.0.0</modelVersion><parent><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-parent</artifactId><version>3.1.2</version><relativePath/></parent><groupId>com.example</groupId><artifactId>swagger-demo-v3</artifactId><version>1.0.0</version><properties><java.version>17</java.version></properties><dependencies><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-web</artifactId></dependency><!-- Springdoc OpenAPI UI --><dependency><groupId>org.springdoc</groupId><artifactId>springdoc-openapi-starter-webmvc-ui</artifactId><version>2.1.0</version></dependency><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-test</artifactId><scope>test</scope></dependency></dependencies><build><plugins><plugin><groupId>org.springframework.boot</groupId><artifactId>spring-boot-maven-plugin</artifactId></plugin></plugins></build>
</project>

4.2 OpenAPI配置类

package com.example.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 org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;@Configuration
public class OpenApiConfig {@Beanpublic OpenAPI customOpenAPI() {return new OpenAPI().info(new Info().title("Spring Boot 3 + OpenAPI 3").version("1.0.0").description("Spring Boot 3 集成 OpenAPI 3 示例").contact(new Contact().name("开发者").url("https://example.com").email("developer@example.com")));}
}

4.3 使用OpenAPI 3注解的Controller

package com.example.controller;import com.example.entity.User;
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.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;import java.util.ArrayList;
import java.util.List;@RestController
@RequestMapping("/api/v3/users")
@Tag(name = "用户管理", description = "用户相关的API接口")
public class UserControllerV3 {private List<User> users = new ArrayList<>();private Long idCounter = 1L;{users.add(new User(idCounter++, "张三", "zhangsan@example.com", 25));users.add(new User(idCounter++, "李四", "lisi@example.com", 30));}@Operation(summary = "获取所有用户", description = "返回系统中的所有用户列表")@ApiResponses(value = {@ApiResponse(responseCode = "200", description = "成功获取用户列表",content = @Content(mediaType = "application/json",schema = @Schema(implementation = User.class))),@ApiResponse(responseCode = "500", description = "服务器内部错误")})@GetMappingpublic List<User> getAllUsers() {return users;}@Operation(summary = "根据ID获取用户", description = "根据用户ID获取特定用户信息")@GetMapping("/{id}")public ResponseEntity<User> getUserById(@Parameter(description = "用户ID", required = true, example = "1")@PathVariable Long id) {User user = users.stream().filter(u -> u.getId().equals(id)).findFirst().orElse(null);return user != null ? ResponseEntity.ok(user) : ResponseEntity.notFound().build();}@Operation(summary = "创建新用户", description = "在系统中创建一个新的用户")@PostMappingpublic User createUser(@RequestBody User user) {user.setId(idCounter++);users.add(user);return user;}
}

4.4 OpenAPI 3实体类注解

package com.example.entity;import io.swagger.v3.oas.annotations.media.Schema;@Schema(description = "用户信息")
public class User {@Schema(description = "用户ID", example = "1")private Long id;@Schema(description = "用户名", example = "张三", requiredMode = Schema.RequiredMode.REQUIRED)private String username;@Schema(description = "邮箱", example = "zhangsan@example.com")private String email;@Schema(description = "年龄", example = "25")private Integer age;// 构造函数和getter/setter省略...
}

4.5 配置文件(Spring Boot 3.x)

# 应用配置
spring.application.name=swagger-demo-v3
server.port=8080# OpenAPI文档配置
springdoc.api-docs.path=/api-docs
springdoc.swagger-ui.path=/swagger-ui.html
springdoc.swagger-ui.operationsSorter=method# 包扫描路径
springdoc.packages-to-scan=com.example.controller

5. 测试Swagger UI功能

5.1 访问文档

  • Springfox (Spring Boot 2.x): http://localhost:8080/swagger-ui.html
  • Springdoc (Spring Boot 3.x): http://localhost:8080/swagger-ui.html

5.2 测试API接口

  1. GET请求测试

    • 点击 "GET /api/users"
    • 点击 "Try it out"
    • 点击 "Execute"
  2. POST请求测试

    • 点击 "POST /api/users"
    • 点击 "Try it out"
    • 在请求体中输入JSON数据:
    {"username": "王五","email": "wangwu@example.com","age": 28
    }
    
    • 点击 "Execute"
  3. PUT/DELETE请求测试

    • 类似操作,填写必要的参数

6. 常见问题和解决方案

6.1 Swagger UI无法访问

问题: 访问swagger-ui.html显示404错误

解决方案:

  1. 检查依赖是否正确添加
  2. 确认配置类是否有@EnableSwagger2注解
  3. 检查Controller包路径配置

6.2 接口不显示

问题: Swagger UI中看不到自定义的接口

解决方案:

// 检查包扫描路径
.apis(RequestHandlerSelectors.basePackage("com.example.controller"))

6.3 生产环境禁用Swagger

@Configuration
@EnableSwagger2
@Profile("!prod")  // 生产环境不加载
public class SwaggerConfig {// 配置内容
}

或使用配置文件:

# application-prod.properties
springfox.documentation.enabled=false

6.4 中文乱码问题

# application.properties
spring.http.encoding.charset=UTF-8
spring.http.encoding.enabled=true
spring.http.encoding.force=true

7. 高级配置

7.1 添加认证配置

@Bean
public Docket createRestApi() {return new Docket(DocumentationType.SWAGGER_2).apiInfo(apiInfo()).select().apis(RequestHandlerSelectors.basePackage("com.example.controller")).paths(PathSelectors.any()).build().securitySchemes(securitySchemes()).securityContexts(securityContexts());
}private List<ApiKey> securitySchemes() {return Lists.newArrayList(new ApiKey("JWT", "Authorization", "header"));
}private List<SecurityContext> securityContexts() {return Lists.newArrayList(SecurityContext.builder().securityReferences(defaultAuth()).forPaths(PathSelectors.regex("/api/.*")).build());
}

7.2 自定义响应模型

@ApiModel("统一响应结果")
public class ApiResponse<T> {@ApiModelProperty("响应代码")private Integer code;@ApiModelProperty("响应消息")private String message;@ApiModelProperty("响应数据")private T data;// 构造函数和getter/setter
}

8. 最佳实践

8.1 注解使用建议

  • 为所有Controller类添加@Api注解
  • 为所有接口方法添加@ApiOperation注解
  • 为实体类字段添加@ApiModelProperty注解
  • 合理使用@ApiImplicitParam@ApiParam

8.2 文档维护

  • 定期更新API文档描述
  • 保持示例数据的准确性
  • 及时更新版本信息

8.3 安全考虑

  • 生产环境禁用Swagger UI
  • 对敏感接口添加适当的安全配置
  • 不要在文档中暴露敏感信息

总结

通过以上步骤,你已经成功集成了Swagger UI到Spring Boot项目中。现在你可以:

  1. ✅ 自动生成API文档
  2. ✅ 在线测试API接口
  3. ✅ 提供给前端开发人员参考
  4. ✅ 提高开发效率

记住选择适合你Spring Boot版本的方案:

  • Spring Boot 2.x 使用 Springfox
  • Spring Boot 3.x 使用 Springdoc OpenAPI

开始使用Swagger,让你的API文档变得生动起来吧!

http://www.dtcms.com/a/343832.html

相关文章:

  • 【学习】CSMM认证与CMMI认证的对比分析
  • logback-spring.xml 文件
  • jenkins实现分布式构建并自动发布到远程服务器上 jenkins实现自动打包编译发布远程服务器
  • 逆向代码笔记
  • 51单片机-驱动步进电机模块教程
  • 移动应用青少年模式开发成本解析:原生、Flutter与Uniapp方案对比-优雅草卓伊凡
  • Redis 数据类型:List 列表的深度解析与应用
  • Apache Ozone 2.0.0集群部署
  • 潇洒郎: Python实现检测鼠标移动和音视频播放行为——打造省电脚本
  • 反催收APP开发思路:用Flutter打造证据链管理工具
  • JVM 调优全流程案例:从频繁 Full GC 到百万 QPS 的实战蜕变
  • 无线数传模块实现实时信号传输,保障煤堆设备生产进度稳定
  • 【LeetCode每日一题】238. 除自身以外数组的乘积
  • 从零开始学习JavaWeb-15
  • 一、anaconda安装与测试运用
  • AlexNet读取数据集 与VGG-11网络
  • 字节Seed-OSS开源,不卷参数卷脑子
  • 防火墙双机热备
  • 【CV】OpenCV①——图形处理简介
  • C#_面向对象设计的艺术
  • [特殊字符] 高可用高并发微服务架构设计:Nginx 与 API Gateway 的协同实践
  • Oracle DB 10g 升级至 11.2.0.4报错-ORA-00132
  • 论文阅读:Do As I Can, Not As I Say: Grounding Language in Robotic Affordances
  • 大模型微调训练资源占用查询:Windows 10 查看 NVIDIA 显卡GPU状态教程(替代 Ubuntu 下 watch nvidia-smi)
  • 从零开始:C语言配置文件解析实战(二)—— 数据解析与键值获取
  • 相机曝光调节与自动曝光控制详解
  • 11、Informer论文笔记
  • 高通Camx相机dump yuv和raw图的抓取方式和查看
  • Linux 软件编程(九)网络编程:IP、端口与 UDP 套接字
  • Jmeter混合业务负载测试指南