Swagger有几个重要特性
代码侵入式注解
遵循YAML文档格式
非常适合三端(PC、iOS及Android)的API管理,尤其适合前后端完全分离的架构模式。
减少没有必要的文档,符合敏捷开发理念
功能强大
作用
接口的文档在线自动生成
功能测试
优点
1. 大大减少前后端的沟通
2. 方便查找和测试接口
3. 提高团队的开发效率
4. 方便新人了解项目
整合swagger
引入依赖
<!-- swagger -->
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger2</artifactId>
<version>2.9.2</version>
</dependency>
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger-ui</artifactId>
<version>2.9.2</version>
</dependency>
配置类
@Configuration
@EnableSwagger2
public class SwaggerConfig {
@Bean
public Docket createRestApi() {
return new Docket(DocumentationType.SWAGGER_2)
//apiInfo指定测试文档基本信息,这部分将在页面展示
.apiInfo(apiInfo())
.select()
//apis() 控制哪些接口暴露给swagger,
// RequestHandlerSelectors.any() 所有都暴露
// RequestHandlerSelectors.basePackage("com.info.*") 指定包位置
.apis(RequestHandlerSelectors.basePackage("com.cbw.admin"))
.paths(PathSelectors.any())
.build();
}
//基本信息,页面展示
private ApiInfo apiInfo() {
return new ApiInfoBuilder()
.title("接口文档")
.description("接口描述")
//联系人实体类
.contact(
new Contact(null, null, null)
)
//版本号
.version("1.0.0")
.build();
}
}
常用注解
swagger通过在controller中,声明注解,API文档进行说明
1、@Api():用在请求的类上,表示对类的说明,也代表了这个类是swagger2的资源
2、@ApiOperation():用于方法,表示一个http请求访问该方法的操作
3、@ApiModel():用于响应实体类上,用于说明实体作用
4、@ApiModelProperty:用在属性上,描述实体类的属性
5、@ApiImplicitParams:用在请求的方法上,包含多@ApiImplicitParam
6、@ApiImplicitParam:用于方法,表示单独的请求参数
7、@ApiParam():用于方法,参数,字段说明 表示对参数的要求和说明
8、@ApiResponses:用于请求的方法上,根据响应码表示不同响应
一个@ApiResponses包含多个@ApiResponse
9、@ApiResponse:用在请求的方法上,表示不同的响应
10、@ApiIgnore():用于类或者方法上,不被显示在页面上
使用
实体类
@ApiModel("用户对象模型")
public class User {
private Long id;
private String username;
private String password;
private String email;
}
controller
/**
* /user post 新增
* /{id} delete 删除
* /{id} put 更新
* /{id} get 根据id加载
* /list-page post 分页查询
*/
@RestController
@RequestMapping("/user")
@Api(tags = {"用户管理API"})
public class UserController {
@PostMapping
@ApiOperation(value = "新增用户", notes = "新增后返回当前用户")
@ApiResponses({
@ApiResponse(code = 200, message = "返回成功", response = User.class),
@ApiResponse(code = 400, message = "参数没有填好(id==1)", response = User.class),
@ApiResponse(code = 401, message = "权限不足(id==1)", response = User.class),
})
public ResponseEntity<User> add(User user) {
if (user.getId() == 1) {
return new ResponseEntity<>(user, HttpStatus.BAD_REQUEST); //400
} else if (user.getId() == 2) {
return new ResponseEntity<>(user, HttpStatus.UNAUTHORIZED); //401
} else {
return ResponseEntity.ok(user);
}
}
@PutMapping
@ApiOperation(value = "修改用户", notes = "修改后返回当前用户")
@ApiResponses({
@ApiResponse(code = 200, message = "返回成功", response = User.class),
@ApiResponse(code = 400, message = "参数没有填好(id==1)", response = User.class),
@ApiResponse(code = 401, message = "权限不足(id==1)", response = User.class),
})
public ResponseEntity<User> update(User user) {
if (user.getId() == 1) {
return new ResponseEntity<>(user, HttpStatus.BAD_REQUEST); //400
} else if (user.getId() == 2) {
return new ResponseEntity<>(user, HttpStatus.UNAUTHORIZED); //401
} else {
return ResponseEntity.ok(user);
}
}
@DeleteMapping("/{id}")
@ApiOperation(value = "删除用户", notes = "删除后返回当前id")
@ApiResponses({
@ApiResponse(code = 200, message = "返回成功", response = User.class),
@ApiResponse(code = 400, message = "参数没有填好(id==1)", response = User.class),
@ApiResponse(code = 401, message = "权限不足(id==1)", response = User.class),
})
@ApiImplicitParam(paramType = "path", name = "id", value = "用户主键ID", required = true)
public ResponseEntity<Long> delete(@PathVariable Long id) {
if (id == 1) {
return new ResponseEntity<>(id, HttpStatus.BAD_REQUEST); //400
} else if (id == 2) {
return new ResponseEntity<>(id, HttpStatus.UNAUTHORIZED); //401
} else {
return ResponseEntity.ok(id);
}
}
@GetMapping("/{id}")
@ApiIgnore
public ResponseEntity<Long> toUpdate(@PathVariable Long id) {
if (id == 1) {
return new ResponseEntity<>(id, HttpStatus.BAD_REQUEST); //400
} else if (id == 2) {
return new ResponseEntity<>(id, HttpStatus.UNAUTHORIZED); //401
} else {
return ResponseEntity.ok(id);
}
}
@PostMapping("/list-page")
@ApiOperation(value = "分页查询", notes = "得到分页查询对象pageInfo")
@ApiImplicitParams({
@ApiImplicitParam(paramType = "query", name = "pageNum", value = "当前页", required = false, defaultValue = "1"),
@ApiImplicitParam(paramType = "query", name = "pageSize", value = "每页行数", required = false, defaultValue = "10")
})
public ResponseEntity<String> findByPage(@RequestParam(defaultValue = "1", required = false) Integer pageNum,
@RequestParam(defaultValue = "10", required = false) Integer pageSize) {
return ResponseEntity.ok("find page result...");
}
}
启动项目,输入localhost:端口号/swagger-ui.html
整合Knife4j
springfox-swagger-ui 的界面就是上面这个样子,有一些缺陷,比如请求参数为 JSON 的时候没办法格式化,返回json结果没办法折叠,没有提供搜索功能等。
Knife4j 的前身是 swagger-bootstrap-ui,是 springfox-swagger-ui 的增强 UI 实现。swagger-bootstrap-ui 采用的是前端 UI 混合后端 Java 代码的打包方式,在微服务的场景下显得非常臃肿,改良后的 Knife4j 更加小巧、轻量,并且功能更加强大。
swagger-bootstrap-ui 增强后如下。单纯从直观体验上来看,确实增强了
第一步,在 pom.xml 文件中添加 Knife4j 的依赖(不需要再引入 springfox-boot-starter)
<dependency>
<groupId>com.github.xiaoymin</groupId>
<artifactId>knife4j-spring-boot-starter</artifactId>
<!--在引用时请在maven中央仓库搜索3.X最新版本号-->
<version>3.0.2</version>
</dependency>
第二步,在 Java 配置类上添加 @EnableOpenApi 注解,开启 Knife4j 增强功能