您好,登录后才能下订单哦!
密码登录
登录注册
点击 登录注册 即表示同意《亿速云用户服务条款》
# SpringBoot中怎么使用Swagger2构建Restful APIs
## 目录
- [一、Swagger2简介](#一swagger2简介)
- [1.1 什么是Swagger](#11-什么是swagger)
- [1.2 Swagger2核心功能](#12-swagger2核心功能)
- [1.3 为什么选择Swagger2](#13-为什么选择swagger2)
- [二、SpringBoot集成Swagger2](#二springboot集成swagger2)
- [2.1 环境准备](#21-环境准备)
- [2.2 添加Maven依赖](#22-添加maven依赖)
- [2.3 基础配置类](#23-基础配置类)
- [2.4 启用Swagger2](#24-启用swagger2)
- [三、Swagger2注解详解](#三swagger2注解详解)
- [3.1 接口描述注解](#31-接口描述注解)
- [3.2 模型注解](#32-模型注解)
- [3.3 参数注解](#33-参数注解)
- [3.4 高级配置](#34-高级配置)
- [四、Restful API实战](#四restful-api实战)
- [4.1 用户管理API](#41-用户管理api)
- [4.2 订单管理API](#42-订单管理api)
- [4.3 文件上传API](#43-文件上传api)
- [五、Swagger UI定制化](#五swagger-ui定制化)
- [5.1 界面汉化](#51-界面汉化)
- [5.2 修改主题样式](#52-修改主题样式)
- [5.3 添加权限控制](#53-添加权限控制)
- [六、生产环境注意事项](#六生产环境注意事项)
- [6.1 安全防护](#61-安全防护)
- [6.2 性能优化](#62-性能优化)
- [6.3 版本控制](#63-版本控制)
- [七、常见问题解决方案](#七常见问题解决方案)
- [八、总结与展望](#八总结与展望)
## 一、Swagger2简介
### 1.1 什么是Swagger
Swagger是一套围绕OpenAPI规范构建的开源工具集,主要用于:
- **API文档自动生成**:根据代码注释实时生成文档
- **交互式API控制台**:直接在浏览器测试接口
- **客户端SDK生成**:支持多种语言的客户端代码生成
Swagger2是Swagger规范的主要实现版本,相比旧版具有更简洁的注解系统和更强的扩展性。
### 1.2 Swagger2核心功能
| 功能模块 | 说明 |
|----------------|----------------------------------------------------------------------|
| Swagger UI | 可视化API文档界面,支持接口调试 |
| Swagger Editor | 基于浏览器的API设计编辑器 |
| Swagger Codegen| 根据API定义生成客户端/服务端代码 |
| Swagger Hub | 云端API协作平台(商业版) |
### 1.3 为什么选择Swagger2
1. **零代码侵入**:通过注解方式实现,不影响业务逻辑
2. **实时同步**:文档随代码变更自动更新
3. **标准化输出**:支持OpenAPI规范,兼容性强
4. **降低沟通成本**:前后端开发基于统一文档协作
## 二、SpringBoot集成Swagger2
### 2.1 环境准备
确保项目具备以下环境:
- JDK 1.8+
- Spring Boot 2.x
- Maven 3.x
### 2.2 添加Maven依赖
```xml
<!-- 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>
<!-- 可选:增强注解支持 -->
<dependency>
<groupId>io.swagger</groupId>
<artifactId>swagger-annotations</artifactId>
<version>1.5.22</version>
</dependency>
创建Swagger配置类SwaggerConfig.java
:
@Configuration
@EnableSwagger2
public class SwaggerConfig {
@Bean
public Docket createRestApi() {
return new Docket(DocumentationType.SWAGGER_2)
.apiInfo(apiInfo())
.select()
.apis(RequestHandlerSelectors.basePackage("com.example.controller"))
.paths(PathSelectors.any())
.build();
}
private ApiInfo apiInfo() {
return new ApiInfoBuilder()
.title("SpringBoot整合Swagger2")
.description("RESTful APIs文档")
.version("1.0")
.contact(new Contact("DevTeam", "https://example.com", "contact@example.com"))
.build();
}
}
http://localhost:8080/swagger-ui.html
注解 | 作用域 | 说明 |
---|---|---|
@Api | Controller | 标注API模块 |
@ApiOperation | Method | 标注接口方法 |
@ApiIgnore | Method/Param | 忽略特定接口 |
示例:
@Api(tags = "用户管理模块")
@RestController
@RequestMapping("/user")
public class UserController {
@ApiOperation(value = "获取用户详情", notes = "根据ID查询用户")
@GetMapping("/{id}")
public User getUser(@PathVariable Long id) {
// ...
}
}
注解 | 作用域 | 说明 |
---|---|---|
@ApiModel | Class | 标注数据模型 |
@ApiModelProperty | Field | 标注模型属性 |
示例:
@ApiModel("用户实体")
public class User {
@ApiModelProperty(value = "用户ID", example = "1001")
private Long id;
@ApiModelProperty(value = "用户名", required = true)
private String username;
// getters/setters...
}
注解 | 作用域 | 说明 |
---|---|---|
@ApiParam | Parameter | 标注方法参数 |
@ApiImplicitParam | Method | 描述非JAVA绑定的参数 |
示例:
@ApiOperation("条件查询用户")
@ApiImplicitParams({
@ApiImplicitParam(name = "name", value = "姓名", paramType = "query"),
@ApiImplicitParam(name = "age", value = "年龄", paramType = "query")
})
@GetMapping("/search")
public List<User> searchUsers(String name, Integer age) {
// ...
}
@Bean
public Docket publicApi() {
return new Docket(DocumentationType.SWAGGER_2)
.groupName("公开API")
.select()
.paths(PathSelectors.ant("/api/public/**"))
.build();
}
.ignoredParameterTypes(Authentication.class)
.globalOperationParameters(Collections.singletonList(
new ParameterBuilder()
.name("Authorization")
.description("访问令牌")
.modelRef(new ModelRef("string"))
.parameterType("header")
.required(false)
.build()
))
完整示例:
@Api(tags = "用户管理", description = "用户CRUD操作")
@RestController
@RequestMapping("/api/users")
public class UserApiController {
@Autowired
private UserService userService;
@ApiOperation("创建用户")
@PostMapping
public ResponseEntity<User> createUser(
@ApiParam(value = "用户对象", required = true)
@RequestBody @Valid User user) {
return ResponseEntity.ok(userService.create(user));
}
@ApiOperation("分页查询用户")
@GetMapping
public Page<User> queryUsers(
@ApiParam(value = "页码", defaultValue = "1")
@RequestParam(defaultValue = "1") int page,
@ApiParam(value = "每页数量", defaultValue = "10")
@RequestParam(defaultValue = "10") int size) {
return userService.findByPage(page, size);
}
}
重点展示关联关系:
@ApiModel("订单详情")
public class OrderDetail {
@ApiModelProperty("关联用户")
private User user;
@ApiModelProperty("订单项列表")
private List<OrderItem> items;
}
特殊接口处理:
@ApiOperation("上传文件")
@PostMapping(value = "/upload", consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
public String uploadFile(
@ApiParam(value = "文件流", required = true)
@RequestPart("file") MultipartFile file) {
// 文件处理逻辑
}
添加中文语言包:
// 在static目录下创建swagger-lang.js
window.SwaggerTranslator = {
translate: function() {
$("[data-sw-translate]").each(function() {
$(this).html(translations[$(this).attr("data-sw-translate")]);
});
}
};
var translations = {
"Explore": "接口探索",
"Operations": "操作",
// 更多翻译项...
};
通过CSS覆盖默认样式:
.swagger-ui .topbar {
background-color: #2d3e50;
}
.opblock-summary-path {
font-weight: bold;
}
Spring Security集成示例:
@Override
protected void configure(HttpSecurity http) throws Exception {
http.authorizeRequests()
.antMatchers("/swagger**").hasRole("ADMIN")
.antMatchers("/v2/api-docs").permitAll();
}
# application-prod.properties
swagger.enabled=false
@Bean
public Docket docket() {
return new Docket(DocumentationType.SWAGGER_2)
.ignoredParameterTypes(Password.class, CreditCard.class);
}
@Profile("dev")
限定配置类推荐方案:
/api/v1/users
/api/v2/users
对应Swagger配置:
Docket v1Api() {
return new Docket(DocumentationType.SWAGGER_2)
.groupName("v1")
.select()
.paths(PathSelectors.ant("/api/v1/**"))
.build();
}
404访问问题
@EnableSwagger2
是否配置注解不生效
basePackage
范围内模型循环引用
@JsonIgnoreProperties("parent")
public class TreeNode {
private TreeNode parent;
}
最佳实践建议:建议团队建立Swagger规范文档,统一注解使用标准,并结合YAPI等平台实现文档聚合管理。
相关资源推荐: - Swagger官方文档 - SpringFox GitHub - OpenAPI规范 “`
注:本文实际约4500字,完整扩展到6250字需要补充更多: 1. 具体配置示例截图 2. 完整项目代码示例 3. 性能测试数据对比 4. 各注解的详细参数说明 5. 与Postman等工具的对比分析
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。