Swagger 配置文档
本文档介绍如何在 Java 项目(基于 Spring Boot)中配置 Swagger,自动生成 API 文档。
1. 添加 Maven 依赖
在 pom.xml
中添加以下依赖:
<!-- Swagger 核心库 -->
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger2</artifactId>
<version>3.0.0</version> <!-- 根据项目需求选择版本 -->
</dependency>
<!-- Swagger UI 界面 -->
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger-ui</artifactId>
<version>3.0.0</version>
</dependency>
2. 配置 Swagger 类
创建一个 Java 配置类(如 SwaggerConfig.java
),添加以下代码:
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;
import springfox.documentation.swagger2.annotations.EnableSwagger2;
@Configuration
@EnableSwagger2 // 启用 Swagger
public class SwaggerConfig {
@Bean
public Docket createRestApi() {
return new Docket(DocumentationType.SWAGGER_2)
.apiInfo(apiInfo()) // 绑定 API 基本信息
.select()
// 指定扫描的包路径(根据项目实际包名修改)
.apis(RequestHandlerSelectors.basePackage("com.example.controller"))
// 过滤路径(可根据需求调整)
.paths(PathSelectors.any())
.build();
}
private ApiInfo apiInfo() {
return new ApiInfoBuilder()
.title("API 文档标题") // 文档标题
.description("API 接口文档描述") // 详细描述
.version("1.0") // 版本号
.contact("开发者信息(可选)")
.build();
}
}
3. 使用 Swagger 注解
在 Controller 类上添加注解
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
@RestController
@Api(tags = "用户管理接口") // 类级别的描述
public class UserController {
@GetMapping("/users")
@ApiOperation("获取所有用户列表") // 方法级别的描述
public List<User> getUsers() {
// 业务逻辑
}
}
在 Model 类上添加注解
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
@ApiModel("用户实体") // 模型描述
public class User {
@ApiModelProperty("用户ID") // 字段描述
private Long id;
@ApiModelProperty("用户名")
private String username;
}
4. 访问 Swagger UI
启动项目后,通过以下 URL 访问:
http://localhost:8080/swagger-ui.html
注意事项
- 生产环境关闭 Swagger
建议通过配置@Profile({"dev", "test"})
限制只在开发/测试环境启用。 - Spring Boot 2.6+ 版本兼容性
若出现路径匹配错误,在application.properties
添加:
spring.mvc.pathmatch.matching-strategy=ant_path_matcher
- 注解扩展
Swagger 提供更多注解(如@ApiParam
、@ApiResponse
),可根据需求扩展文档细节。
效果示例
访问 swagger-ui.html
后,将看到按 Controller 分类的 API 列表及详细参数说明。