Spring Boot 使用swagger2
swagger2可以减少我们的编写文档工作,尤其现在是前后端分离。后端写好接口之后还需要写API使用文档给客户端人员,尤其是在接口变更之后,文档往往就得不到即使的更新甚至是遗忘,导致文档最总变得不可信,这个框架可以帮助解决此类问题,减少后端人员的工作量,同时还能保持维护文档的地方只有一处。
这个框架也只是帮助减少上述问题,如果只是修改代码,而没有更新相应的描述信息等,也是会存在上述问题的。
一、准备工作
添加依赖,在pom.xml文件中添加如下依赖:
<!-- swagger2 -->
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger2</artifactId>
<version>2.8.0</version>
</dependency>
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger-ui</artifactId>
<version>2.8.0</version>
</dependency>
二、配置swagger2
在启动类同目录下,新建一个Swagger2类,其中注意createRestApi方法下的包名为自己项目中的包名,一般为控制器(controller)所在的包。
package com.pingan.schedule;
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.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2;
/**
* @author: 焦立伟
* @PackageName: com.pingan.schedule
* @ClassName: Swagger2
* @Description:
* @date: 2019/11/29 17:16
*/
@Configuration
@EnableSwagger2
public class Swagger2 {
//指定扫描包的路径来指定要创建的api的目录,一般是控制器这个包
@Bean
public Docket createRestApi(){
return new Docket(DocumentationType.SWAGGER_2)
.apiInfo(apiInfo())
.select()
.apis(RequestHandlerSelectors.basePackage("com.pingan.schedule.controller"))
.paths(PathSelectors.any())
.build();
}
//设置API的基本信息
private ApiInfo apiInfo(){
return new ApiInfoBuilder()
.title("config实验")
.description("后端接口说明文档")
.termsOfServiceUrl("连接地址")
.version("1.0")
.build();
}
}
三、swagger2常用注解说明
-
@Api( ) 写在controller类名上边
value: 不显示在swagger上
tags: 会显示,一个字符串,说明整个类的作用以名称。
@Api(value = "Welcom", tags = {"User Guide"})
public class HelloController {
}
-
@ApiOperation() 在方法名上边,方法说明作用
value: 说明方法的用途、作用
notes: 方法的备注说明
httpMethod: 指定请求方式
@GetMapping("/hi")
@ApiOperation(value = "问候语", notes = "这是一个问候", httpMethod = "GET")
public String hello() {
return "Hell World";
}
-
@ApilmplicitParams
是一个@ApilmplicitParams 参数数组,用在请求的方法上,包含一组参数说明。 -
@ApilmplicitParam 表示参数数组中的每一项
name: 参数名
value:参数的汉字说明,描述信息
required:是否需要
dataType:参数类型,默认String、Integer、Long、对象等
defaultValue: 参数的默认值
paramType: 参数放在哪个地方
例如:
@RequestMapping(value = "/update/{id}", method = RequestMethod.PUT)
@ApiOperation(value = "更新信息", notes = "根据url的id来指定更新用户信息")
@ApiImplicitParams({
@ApiImplicitParam(name = "id", value = "用户ID", required = true, dataType = "Long", paramType = "path"),
@ApiImplicitParam(name = "user", value = "用户实体", required = true, dataType = "User")
})
public String putUser(@PathVariable Long id, @RequestBody User user) {
System.out.println(id);
System.out.println(user.getId());
System.out.println(user.getName());
return "修改成功";
}
-
@ApiParam 请求参数说明,用于方法中
name:参数名
value:参数的汉字说明,表述信息
required:是否必需
@ApiOperation("更改用户信息")
@PostMapping("/updateUserInfo")
public int test(@RequestBody @ApiParam(name = "用户对象", value = "传入json格式", required = true) User user) {
return 1;
}
- @ApiResponses 是一个@ApiResponse的数组,用于请求的方法上,表示一组相应
-
@ApiResponse() 表示相应数组中的每一项
code:标准的http响应码,例如404、500、401等
message:错误信息,例如:参数错误
response:抛出异常的类
修饰在方法上,表达一个错误的相应,例如:
@GetMapping("/hi")
@ApiOperation(value = "问候语", notes = "这是一个问候", httpMethod = "GET")
@ApiResponses({
@ApiResponse(code = 400, message = "请求参数没填好"),
@ApiResponse(code = 401, message = "没有授权"),
@ApiResponse(code = 403, message = "被禁止访问"),
@ApiResponse(code = 404, message = "请求路径没有或页面跳转路径不对")
})
public String hello() {
return "Hello World";
}
- @PathVariable 表示请求某一个参数,用在方法中
- @RequestBody 表示请求的对象参数,用在方法中
public String putUser(@PathVariable Long id, @RequestBody User user) {
System.out.println(id);
System.out.println(user.getId());
System.out.println(user.getName());
return "修改成功";
}
-
@ApiModel 用于参数为一个实体类时,说明这个类的各项属性的含义,只能修饰在类上,需要配合@ApiModelProperty一起使用
value:类名
description:描述
-@ApiModelProperty() 修饰实体类的属性
name:属性名称
value:描述
dataType:属性的数据类型
required:是否必填
example:举例说明
hidden:在文档上是否不可见
@ApiModel
public class User implements Serializable {
@ApiModelProperty(value = "用户id",name = "id",required = false)
private Long id;
@ApiModelProperty(value = "用户名称",name = "name", required = true, example = "张三")
private String name;
}
四、项目中使用
用户实体类
@ApiModel
public class User implements Serializable {
@ApiModelProperty(value = "用户id",name = "id",required = false)
private Long id;
@ApiModelProperty(value = "用户名称",name = "name", required = true, example = "张三")
private String name;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
@Override
public String toString() {
return "User{" +
"id=" + id +
", name='" + name + '\'' +
'}';
}
}
controller控制器
@RestController
@RequestMapping("/api")
@Api(value = "Welcom", tags = {"User Guide"})
public class HelloController {
@GetMapping("/hi")
@ApiOperation(value = "问候语", notes = "这是一个问候", httpMethod = "GET")
@ApiResponses({
@ApiResponse(code = 400, message = "请求参数没填好"),
@ApiResponse(code = 401, message = "没有授权"),
@ApiResponse(code = 403, message = "被禁止访问"),
@ApiResponse(code = 404, message = "请求路径没有或页面跳转路径不对")
})
public String hello() {
return "Hello World";
}
/*
* @Author 焦立伟
* @Description
* @Date 18:54 2019/11/29
* @Param
* @return 返回一个对象
**/
@GetMapping("/list")
@ApiOperation(value = "列表", notes = "获取用户列表")
public HttpResult list() {
HttpResult httpResult = new HttpResult();
httpResult.setCode(0L);
httpResult.setMsg("");
List<User> list = new ArrayList<>();
User user = new User();
user.setId(1L);
user.setName("王五");
list.add(user);
httpResult.setData(list);
return httpResult;
}
@RequestMapping(value = "/find/{id}", method = RequestMethod.GET)
@ApiOperation(value = "查找用户", notes = "更具id查找某个用户的信息")
@ApiImplicitParam(name = "id", value = "用户唯一标识", required = true, dataType = "Long", paramType = "path")
public User getBook(@PathVariable Long id) {
System.out.println("传入的id:" + id);
User user = new User();
user.setId(1L);
user.setName("库里");
return user;
}
@RequestMapping(value = "/add", method = RequestMethod.POST)
@ApiOperation(value = "添加用户", notes = "添加一个新用户")
@ApiImplicitParam(name = "user", value = "用户详细实体", required = true, dataType = "User")
public String postBook(@RequestBody User user) {
System.out.println("添加传入的User:" + user.toString());
return "添加用户成功";
}
@RequestMapping(value = "/update/{id}", method = RequestMethod.PUT)
@ApiOperation(value = "更新信息", notes = "更新指定用户的信息")
@ApiImplicitParams({
@ApiImplicitParam(name = "id", value = "用户ID", required = true, dataType = "Long"),
@ApiImplicitParam(name = "user", value = "用户实体", required = true, dataType = "User"),
})
public String putUser(@PathVariable Long id, @RequestBody User user) {
System.out.println(id);
System.out.println(user.getId());
System.out.println(user.getName());
return "修改成功";
}
@RequestMapping(value = "/del_user/{id}", method = RequestMethod.DELETE)
@ApiOperation(value = "删除用户", notes = "根据id来删除指定用户")
@ApiImplicitParam(name = "id", value = "用户ID", required = true, dataType = "Long")
public String deleteUser(@PathVariable Long id) {
System.out.println("删除用户id:" + id);
return "删除成功";
}
}
最后运行项目,然后在浏览器中打开 http://localhost:8080/swagger-ui.html ,即可看到swagger界面。