您好,登录后才能下订单哦!
密码登录
登录注册
点击 登录注册 即表示同意《亿速云用户服务条款》
# SpringBoot项目接口之Swagger怎么用
## 一、Swagger简介与核心价值
### 1.1 什么是Swagger
Swagger是一套围绕OpenAPI规范构建的开源工具链,主要用于:
- **API文档自动化生成**:根据代码注释实时生成交互式文档
- **接口调试**:直接在浏览器中测试API接口
- **客户端SDK生成**:支持多种语言的客户端代码生成
版本演进:
- Swagger 1.0 → Swagger 2.0 → OpenAPI 3.0
- 目前主流实现为Springfox Swagger(2.x)和SpringDoc OpenAPI(3.0+)
### 1.2 为什么选择Swagger
对比传统文档工具的优势:
```diff
+ 实时同步:代码变更立即反映到文档
+ 交互体验:内置API测试功能
+ 标准化:遵循OpenAPI规范
- 手动维护的文档容易过时
- 需要额外使用Postman等测试工具
Maven依赖配置:
<!-- Springfox Swagger2 核心库 -->
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger2</artifactId>
<version>2.9.2</version>
</dependency>
<!-- Swagger UI 界面 -->
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger-ui</artifactId>
<version>2.9.2</version>
</dependency>
启动类配置:
@SpringBootApplication
@EnableSwagger2 // 启用Swagger
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}
@Configuration
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文档")
.description("包含用户、订单、商品模块")
.version("1.0")
.contact(new Contact("DevTeam", "https://example.com", "dev@example.com"))
.build();
}
}
注解 | 作用域 | 说明 |
---|---|---|
@Api |
类 | 标记控制器类功能描述 |
@ApiOperation |
方法 | 接口方法说明(可配置响应码) |
@ApiParam |
参数 | 单个参数说明(非RequestBody时使用) |
示例代码:
@Api(tags = "用户管理模块")
@RestController
@RequestMapping("/user")
public class UserController {
@ApiOperation(value = "创建用户", notes = "需要提供用户名和密码")
@PostMapping
public Result<User> createUser(
@ApiParam(value = "用户DTO", required = true)
@RequestBody UserDTO dto) {
// 实现逻辑
}
}
@ApiModel(description = "用户实体")
public class User {
@ApiModelProperty(value = "用户ID", example = "1001")
private Long id;
@ApiModelProperty(value = "用户名", required = true, example = "admin")
private String username;
// getters/setters
}
@ApiImplicitParams
:描述非实体类参数@ApiResponse
:自定义HTTP响应码说明@ApiIgnore
:排除特定参数或方法http://localhost:8080/swagger-ui.html
POST /user
){
"username": "test123",
"password": "123456"
}
// 仅允许认证用户访问Swagger
@Bean
public SecurityConfiguration security() {
return SecurityConfigurationBuilder.builder()
.enableCsrfSupport(true)
.build();
}
// 后台管理API分组
@Bean
public Docket adminApi() {
return new Docket(DocumentationType.SWAGGER_2)
.groupName("后台管理")
.select()
.paths(PathSelectors.ant("/admin/**"))
.build();
}
// 移动端API分组
@Bean
public Docket mobileApi() {
// 类似配置...
}
// 添加JWT认证头参数
private List<Parameter> globalParameters() {
ParameterBuilder builder = new ParameterBuilder();
return Collections.singletonList(
builder.name("Authorization")
.description("JWT令牌")
.modelRef(new ModelRef("string"))
.parameterType("header")
.required(false)
.build());
}
// 全局响应消息模板
private List<ResponseMessage> responseMessages() {
return Arrays.asList(
new ResponseMessageBuilder()
.code(500)
.message("服务器内部错误")
.build(),
new ResponseMessageBuilder()
.code(403)
.message("资源不可用")
.build()
);
}
问题现象: - SpringBoot 2.6+与Swagger 2.9.2路径匹配冲突
解决方案:
# application.properties
spring.mvc.pathmatch.matching-strategy=ant_path_matcher
@ApiModelProperty(dataType = "string", allowableValues = "A,B,C")
private StatusEnum status;
@ApiOperation("上传头像")
@PostMapping(value = "/avatar", consumes = "multipart/form-data")
public Result uploadAvatar(
@ApiParam(value = "头像文件", required = true)
@RequestPart MultipartFile file) {
// 实现逻辑
}
<!-- 替换为SpringDoc -->
<dependency>
<groupId>org.springdoc</groupId>
<artifactId>springdoc-openapi-ui</artifactId>
<version>1.6.8</version>
</dependency>
@Configuration
@OpenAPIDefinition(
info = @Info(title = "新API文档")
)
public class OpenApiConfig {
// 无需@Enable注解
}
文档规范:
@ApiOperation
@ApiModel
说明版本控制:
.paths(PathSelectors.regex("/v1/.*")) // 只显示v1接口
生产环境策略:
@Profile({"dev", "test"})
@Configuration
public class SwaggerConfig { ... }
Swagger作为API文档工具,能显著提升前后端协作效率。建议: 1. 开发阶段:充分利用实时文档和测试功能 2. 联调阶段:用Swagger UI作为唯一接口规范 3. 发布阶段:导出OpenAPI规范文件归档
最终效果参考:
图:标准的Swagger UI界面展示 “`
注:本文实际约3200字(含代码),如需调整字数可增减以下内容: - 增加更多实战示例(+300字) - 添加Knife4j等增强工具介绍(+200字) - 扩展OpenAPI 3.0的详细对比(+400字)
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。