# SpringBoot集成Swagger2
**Repository Path**: jianml/swagger2
## Basic Information
- **Project Name**: SpringBoot集成Swagger2
- **Description**: SpringBoot集成Swagger2
- **Primary Language**: Java
- **License**: Not specified
- **Default Branch**: master
- **Homepage**: None
- **GVP Project**: No
## Statistics
- **Stars**: 2
- **Forks**: 0
- **Created**: 2019-11-11
- **Last Updated**: 2021-12-22
## Categories & Tags
**Categories**: Uncategorized
**Tags**: None
## README
# SpringBoot集成Swagger2
### Swagger2优点
整合到Spring Boot中,构建强大RESTful API文档。省去接口文档管理工作,修改代码,自动更新,Swagger2也提供了强大的页面测试功能来调试RESTful API。
### 项目搭建
#### maven依赖
```xml
io.springfox
springfox-swagger2
2.8.0
io.springfox
springfox-swagger-ui
2.8.0
```
#### 新建配置类
Swagger2的配置也是比较容易的,在项目创建成功之后,只需要开发者自己提供一个Docket的Bean即可,如下:
```java
package cn.jian.swagger2.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;
/**
* Swagger配置类
* @author: wujian
* @time: 2019/11/11
*/
@Configuration
@EnableSwagger2
public class SwaggerConfig {
/**
* 通过 createRestApi函数来构建一个DocketBean
* 函数名,可以随意命名,喜欢什么命名就什么命名
* @return
*/
@Bean
public Docket createRestApi() {
return new Docket(DocumentationType.SWAGGER_2)
.apiInfo(apiInfo())//调用apiInfo方法,创建一个ApiInfo实例,里面是展示在文档页面信息内容
.select()
//控制暴露出去的路径下的实例
//如果某个接口不想暴露,可以使用以下注解
//@ApiIgnore 这样,该接口就不会暴露在 swagger2 的页面下
.apis(RequestHandlerSelectors.basePackage("cn.jian.swagger2"))
.paths(PathSelectors.any())
.build();
}
/**
* 构建 api文档的详细信息函数
*/
private ApiInfo apiInfo() {
return new ApiInfoBuilder()
//页面标题
.title("Spring Boot Swagger2 构建RESTful API")
//条款地址
.termsOfServiceUrl("https://gitee.com/jianml/swagger2")
.contact(new Contact("Jian Wu", "http://jianml.cn", "792622917@qq.com"))
.version("1.0")
//描述
.description("API 描述")
.build();
}
}
```
这里提供一个配置类,首先通过@EnableSwagger2注解启用Swagger2,然后配置一个Docket Bean,这个Bean中,配置映射路径和要扫描的接口的位置,在apiInfo中,主要配置一下Swagger2文档网站的信息,例如网站的title,网站的描述,联系人的信息,使用的协议等等。
如果不想将所有的接口都通过swagger管理的话,可以将`RequestHandlerSelectors.any()`修改为`RequestHandlerSelectors.basePackage()`
如此,Swagger2就算配置成功了,非常方便。
#### 创建User实体类
```java
package cn.jian.swagger2.entity;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;
/**
* 用户实体类
* @author: wujian
* @time: 2019/11/11
*/
@ApiModel
@Data
public class User {
/**
* 用户ID
*/
@ApiModelProperty(name = "id", value = "用户ID", required = true)
private Integer id;
/**
* 用户名
*/
@ApiModelProperty(name = "username", value = "用户名", required = true)
private String username;
/**
* 密码
*/
@ApiModelProperty(name = "password", value = "密码", required = true)
private String password;
/**
* 邮箱
*/
@ApiModelProperty(name = "email", value = "邮箱", required = false)
private String email;
}
```
#### 创建UserController类
```java
package cn.jian.swagger2.controller;
import User;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.springframework.web.bind.annotation.*;
import springfox.documentation.annotations.ApiIgnore;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* 用户管理相关接口
* @author: wujian
* @time: 2019/11/11
*/
@Api(tags = "用户管理相关接口")
@RestController
@RequestMapping("/user")
public class UserController {
private static Map userMap = new HashMap<>();
@ApiIgnore() // 添加这个注解将不会显示在UI界面上
@ApiOperation(value = "接口的功能介绍", notes = "提示接口使用者注意事项")
@GetMapping("/hello")
public String hello(){
return "hello world!";
}
@ApiOperation("获取用户列表接口")
@GetMapping("/list")
public List listUser(){
return new ArrayList<>(userMap.values());
}
@ApiOperation("添加用户的接口")
@ApiImplicitParam(name = "user", value = "用户详细实体user", required = true, paramType = "body", dataType = "User")
@PostMapping("/")
public void addUser(@RequestBody User user){
userMap.put(user.getId(), user);
}
@ApiOperation("更新用户的接口")
@ApiImplicitParams({
@ApiImplicitParam(name = "id", value = "用户id", required = true, paramType = "path", dataType = "String"),
@ApiImplicitParam(name = "user", value = "用户详细实体user", required = true, paramType = "body", dataType = "User")
})
@PutMapping("/{id}")
public void updateUser(@PathVariable Integer id, @RequestBody User user) {
userMap.remove(id);
userMap.put(user.getId(), user);
}
@ApiOperation("根据id查询用户的接口")
@ApiImplicitParam(name = "id", value = "用户ID", defaultValue = "1", required = true, paramType = "path", dataType = "String")
@GetMapping("/{id}")
public User getUser(@PathVariable Integer id){
if(!userMap.containsKey(id))
return null;
return userMap.get(id);
}
@ApiOperation("根据id删除用户的接口")
@ApiImplicitParam(name = "id", value = "用户ID", defaultValue = "1", required = true, paramType = "path", dataType = "String")
@DeleteMapping("/{id}")
public void deleteUser(@PathVariable Integer id) {
userMap.remove(id);
}
}
```
#### 到这里为止swagger就已经配置完了, 可以启动项目访问
### swagger常用注解
1. @Api:用在类上,标志此类是Swagger资源
| 属性名称 | 备注 |
| :---------- | :----------------------------------------------- |
| value | 该参数没什么意义,在UI界面上不显示,所以不用配置 |
| tags | 说明该类的作用,参数是个数组,可以填多个 |
| description | 对api资源的描述 |
2. @ApiOperation:用在方法上,描述方法的作用
| 属性名称 | 备注 |
| :------- | :---------------------------------------- |
| value | 方法的用途和作用 |
| tags | 方法的标签,可以设置多个值 |
| notes | 方法的注意事项和备注 |
| response | 返回的类型(尽量不写,由swagger扫描生成) |
3. @ApiImplicitParams:包装器:包含多个ApiImplicitParam对象列表
| 属性名称 | 备注 |
| :------- | :----------------------- |
| value | 多个ApiImplicitParam配置 |
4. @ApiParam:用于Controller中方法的参数说明
| 属性名称 | 备注 |
| :-------------- | :----------------------------- |
| name | 属性名称 |
| value | 属性值 |
| defaultValue | 默认属性值 |
| allowableValues | 可以不配置 |
| required | 是否属性必填 |
| allowMultiple | 文件上传时,是否允许多文件上传 |
5. @ApiImplicitParam:定义在@ApiImplicitParams注解中,定义单个参数详细信息,如果只有一个参数,也可以定义在方法上
| 属性名称 | 备注 |
| :----------- | :----------------------------------------------------------- |
| name | 参数名 |
| value | 参数说明 |
| dataType | 参数类型 |
| paramType | 表示参数放在哪里 header : 请求参数的获取:@RequestHeader query : 请求参数的获取:@RequestParam path : 请求参数的获取:@PathVariable body : 不常用 form : 不常用 |
| defaultValue | 参数的默认值 |
| required | 参数是否必须传 |
6. @ApiModel:用在类上,表示对类进行说明,用于实体类中的参数接收说明
| 属性名称 | 备注 |
| :---------- | :------------- |
| value | 默认为类的名称 |
| description | 对该类的描述 |
7. @ApiModelProperty:在model类的属性添加属性说明
| 属性名称 | 备注 |
| :-------------- | :----------- |
| value | 属性描述 |
| name | 属性名称 |
| allowableValues | 参数允许的值 |
| dataType | 数据类型 |
| required | 是否必填 |
8. @ApiResponses:包装器:包含多个ApiResponse对象列表
| 属性名称 | 备注 |
| :------- | :------------------ |
| value | 多个ApiResponse配置 |
9. @ApiResponse:定义在@ApiResponses注解中,一般用于描述一个错误的响应信息
| 属性名称 | 备注 |
| :---------------- | :--------------------- |
| code | 响应码 |
| message | 状态码对应的响应信息 |
| response | 默认响应类 Void |
| responseContainer | 参考ApiOperation中配置 |
10. @ApiIgnore():用于类或者方法上,不被显示在页面上
### 总结
除上面之外有点值得注意的是,如果是上传文件的话,需要把`@ApiImplicitParam`中的`dataType`属性配置为`__File`否则在swagger中会显示为文本框而不是上传按钮
> 源码地址: https://gitee.com/jianml/swagger2