Swagger 是一个规范且完整的框架,用于生成、描述、调用和可视化 RESTful 风格的 Web 服务。
通过注解自动生成在线接口文档,包含参数和格式,直接在文档中输入参数对应的值即可在线测试接口。
集成 Swagger
Swagger2
pom.xml
<dependencies>
<!-- 其他... -->
<!-- swagger2 -->
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger2</artifactId>
<version>2.9.2</version>
</dependency>
<!--
不添加这个配置时swagger默认引用的是1.5.20版本,
其中会对一些没有添加注解的位置进行默认参数判断,在进入swagger接口文档首页时会出现一个数据转换错误,
swagger2
i.s.m.p.AbstractSerializableParameter: Illegal DefaultValue null for parameter type integer
java.lang.NumberFormatException: For input string: "" ...
升级版本后对默认属性的判断方式不同,不会出现这个异常
-->
<!-- swagger2 -->
<dependency>
<groupId>io.swagger</groupId>
<artifactId>swagger-annotations</artifactId>
<version>1.5.21</version>
</dependency>
<!-- swagger2 -->
<dependency>
<groupId>io.swagger</groupId>
<artifactId>swagger-models</artifactId>
<version>1.5.21</version>
</dependency>
<!-- swagger2 -->
<!-- 使用 swagger-bootstrap-ui 代替 springfox-swagger-ui -->
<dependency>
<groupId>com.github.xiaoymin</groupId>
<artifactId>swagger-bootstrap-ui</artifactId>
<version>1.9.6</version>
</dependency>
</dependencies>
Swagger3
pom.xml
<dependencies>
<!-- 其他... -->
<!-- 引入Swagger3依赖 -->
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-boot-starter</artifactId>
<version>3.0.0</version>
</dependency>
<!-- Knife4j的前身是swagger-bootstrap-ui,前身swagger-bootstrap-ui是一个纯swagger-ui的ui皮肤项目 -->
<dependency>
<groupId>com.github.xiaoymin</groupId>
<artifactId>knife4j-spring-boot-starter</artifactId>
<version>3.0.2</version>
</dependency>
</dependencies>
配置 Swagger
可以在 application.yml
中配置开关, 适配生产环境
swagger:
enabled: true # 开发环境启用 swagger
knife4j:
enable: true # 开启增强配置
production: false # 开启生产环境屏蔽
Swagger 配置文件 (2 和 3 没有区别)
package com.example.verder.swagger; // 忽略我的 iOS 命名
import org.springframework.beans.factory.annotation.Value;
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.oas.annotations.EnableOpenApi;
import springfox.documentation.service.ApiInfo;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
/**
* @author dk
* @create 2022-06-27 1:48 PM
*/
@Configuration
//@EnableSwagger2 //开启 Swagger2
@EnableOpenApi //开启 Swagger3 ,可不写
@EnableKnife4j //开启 knife4j ,可不写
public class SwaggerConfig {
// 访问地址
// (swagger-ui) http://localhost:8081/xxx/swagger-ui/index.html
// (knife4j / swagger-bootstrap-ui) http://localhost:8081/xxx/doc.html
// 允许匿名访问地址
// /swagger**/**
// /webjars/**
// /v3/**
// /doc.html
/**
* 用于读取配置文件 application.properties 中 swagger 属性是否开启
*/
@Value("${swagger.enabled}")
Boolean swaggerEnabled;
@Bean
public Docket docket() {
// Swagger 2 使用的是:DocumentationType.SWAGGER_2
// Swagger 3 使用的是:DocumentationType.OAS_30
return new Docket(DocumentationType.OAS_30)
.apiInfo(apiInfo())
// 是否开启swagger
.enable(swaggerEnabled)
.select()
// 过滤条件,扫描指定路径下的文件
.apis(RequestHandlerSelectors.basePackage("com.example.api.controller"))
// 指定路径处理,PathSelectors.any()代表不过滤任何路径
.paths(PathSelectors.any())
.build();
}
private ApiInfo apiInfo() {
return new ApiInfoBuilder()
.title("xx接口文档")
.description("xx")
//.contact(new Contact("作者", "作者URL", "作者Email"))
.version("1.0")
.build();
}
}
使用 Swagger
添加注解
package com.example.api.controller;
import io.swagger.annotations.*;
import lombok.Data;
import org.springframework.web.bind.annotation.*;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* @author dk
* @create 2022-06-27 3:05 PM
*/
@Api(tags = {"用户信息管理"})
@RestController
@RequestMapping("/api/test")
public class ApiTestController {
@ApiOperation("获取用户列表")
@GetMapping("/list")
public Map<String, Object> userList() {
List<UserEntity> userList = new ArrayList<UserEntity>();
Map<String, Object> map = new HashMap<>();
map.put("code", 0);
map.put("message", "获取用户列表成功");
map.put("data", userList);
return map;
}
@ApiOperation("获取用户详细")
@ApiImplicitParam(name = "userId", value = "用户ID", required = true, dataType = "int", paramType = "path", dataTypeClass = Integer.class)
@GetMapping("/{userId}")
public Map<String, Object> getUser(@PathVariable Integer userId) {
Map<String, Object> map = new HashMap<>();
map.put("code", 500);
map.put("message", "用户不存在");
return map;
}
@ApiOperation("新增用户")
@ApiImplicitParams({
@ApiImplicitParam(name = "userId", value = "用户id", dataType = "Integer", dataTypeClass = Integer.class),
@ApiImplicitParam(name = "username", value = "用户名称", dataType = "String", dataTypeClass = String.class),
@ApiImplicitParam(name = "password", value = "用户密码", dataType = "String", dataTypeClass = String.class),
@ApiImplicitParam(name = "mobile", value = "用户手机", dataType = "String", dataTypeClass = String.class)
})
@PostMapping("/save")
public Map<String, Object> save(UserEntity user) {
Map<String, Object> map = new HashMap<>();
map.put("code", 0);
map.put("message", "新增用户成功");
map.put("data", user);
return map;
}
@ApiOperation("更新用户")
@PutMapping("/update")
public Map<String, Object> update(@RequestBody UserEntity user) {
Map<String, Object> map = new HashMap<>();
map.put("code", 0);
map.put("message", "更新用户成功");
map.put("data", user);
return map;
}
@ApiOperation("删除用户信息")
@ApiImplicitParam(name = "userId", value = "用户ID", required = true, dataType = "int", paramType = "path", dataTypeClass = Integer.class)
@DeleteMapping("/{userId}")
public Map<String, Object> delete(@PathVariable Integer userId) {
Map<String, Object> map = new HashMap<>();
map.put("code", 0);
map.put("message", "删除用户信息成功");
return map;
}
}
@ApiModel(value = "UserEntity", description = "用户实体")
@Data // get / set ...
class UserEntity {
@ApiModelProperty("用户ID")
private Integer userId;
@ApiModelProperty("用户名称")
private String username;
@ApiModelProperty("用户密码")
private String password;
@ApiModelProperty("用户手机")
private String mobile;
}
测试 Swagger
springfox-swagger-ui
运行项目, 并访问
http://localhost:8180/projectName/swagger-ui.html
http://localhost:8180/projectName/swagger-ui/index.html

Knife4j / swagger-bootstrap-ui
运行项目, 并访问 http://localhost:8180/projectName/doc.html

网友评论