一、为什么使用Swagger2
当下很多公司都采取前后端分离的开发模式,前端和后端的工作由不同的工程师完成。在这种开发模式下,维持一份及时更新且完整的 Rest API 文档将会极大的提高我们的工作效率。传统意义上的文档都是后端开发人员手动编写的,相信大家也都知道这种方式很难保证文档的及时性,这种文档久而久之也就会失去其参考意义,反而还会加大我们的沟通成本。而 Swagger 给我们提供了一个全新的维护 API 文档的方式,下面我们就来了解一下它的优点:
1、代码变,文档变。只需要少量的注解,Swagger 就可以根据代码自动生成 API 文档,很好的保证了文档的时效性。
2、跨语言性,支持 40 多种语言。
3、Swagger UI 呈现出来的是一份可交互式的 API 文档,我们可以直接在文档页面尝试 API 的调用,省去了准备复杂的调用参数的过程。
4、还可以将文档规范导入相关的工具(例如 Postman、SoapUI), 这些工具将会为我们自动地创建自动化测试。
二、Swagger2实用配置
1、工程创建
当然,首先是创建一个Spring Boot项目,加入web依赖,创建成功后,加入两个Swagger2相关的依赖,完整的依赖如下:
<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>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
2、Swagger2配置
Swagger2的配置也是比较容易的,在项目创建成功之后,只需要开发者自己提供一个Docket的Bean即可,如下:
@Configuration
@EnableSwagger2
public class SwaggerConfig {
@Bean
public Docket createRestApi() {
return new Docket(DocumentationType.SWAGGER_2)
.pathMapping("/")
.select()
.apis(RequestHandlerSelectors.basePackage("com.nvn.controller"))
.paths(PathSelectors.any())
.build().apiInfo(new ApiInfoBuilder()
.title("SpringBoot整合Swagger")
.description("SpringBoot整合Swagger,详细信息......")
.version("9.0")
.contact(new Contact("啊啊啊啊","blog.csdn.net","aaa@gmail.com"))
.license("The Apache License")
.licenseUrl("http://www.baidu.com")
.build());
}
}
这里提供一个配置类,首先通过@EnableSwagger2注解启用Swagger2,然后配置一个Docket Bean,这个Bean中,配置映射路径和要扫描的接口的位置,在apiInfo中,主要配置一下Swagger2文档网站的信息,例如网站的title,网站的描述,联系人的信息,使用的协议等等。
如此,Swagger2就算配置成功了,非常方便。
此时启动项目,输入http://localhost:8080/swagger-ui.html,能够看到如下页面,说明已经配置成功了:
3、创建接口
接下来就是创建接口了,Swagger2相关的注解其实并不多,而且很容易懂,下面我来分别向小伙伴们举例说明:
@RestController
@Api(tags = "用户管理相关接口")
@RequestMapping("/user")
public class UserController {
@PostMapping("/")
@ApiOperation("添加用户的接口")
@ApiImplicitParams({
@ApiImplicitParam(name = "username", value = "用户名", defaultValue = "李四"),
@ApiImplicitParam(name = "address", value = "用户地址", defaultValue = "深圳", required = true)
}
)
public RespBean addUser(String username, @RequestParam(required = true) String address) {
return new RespBean();
}
@GetMapping("/")
@ApiOperation("根据id查询用户的接口")
@ApiImplicitParam(name = "id", value = "用户id", defaultValue = "99", required = true)
public User getUserById(@PathVariable Integer id) {
User user = new User();
user.setId(id);
return user;
}
@PutMapping("/{id}")
@ApiOperation("根据id更新用户的接口")
public User updateUserById(@RequestBody User user) {
return user;
}
}
4、注解说明:
这里边涉及到多个API,我来向小伙伴们分别说明:
@Api注解可以用来标记当前Controller的功能。
@ApiOperation注解用来标记一个方法的作用。
@ApiImplicitParam注解用来描述一个参数,可以配置参数的中文含义,也可以给参数设置默认值,这样在接口测试的时候可以避免手动输入。
如果有多个参数,则需要使用多个@ApiImplicitParam注解来描述,多个@ApiImplicitParam注解需要放在一个@ApiImplicitParams注解中。
需要注意的是,@ApiImplicitParam注解中虽然可以指定参数是必填的,但是却不能代替**@RequestParam(required = true)**,前者的必填只是在Swagger2框架内必填,抛弃了Swagger2,这个限制就没用了,所以假如开发者需要指定一个参数必填,@RequestParam(required = true)注解还是不能省略。
如果参数是一个对象(例如上文的更新接口),对于参数的描述也可以放在实体类中。例如下面一段代码:
@ApiModel
public class User {
@ApiModelProperty(value = "用户id")
private Integer id;
@ApiModelProperty(value = "用户名")
private String username;
@ApiModelProperty(value = "用户地址")
private String address;
//getter/setter
}
5、实例
可以看到,所有的接口这里都列出来了,包括接口请求方式,接口地址以及接口的名字等,点开一个接口,可以看到如下信息:
可以看到,接口的参数,参数要求,参数默认值等等统统都展示出来了,参数类型下的query表示参数以key/value的形式传递,点击右上角的Try it out,就可以进行接口测试:
点击Execute按钮,表示发送请求进行测试。测试结果会展示在下面的Response中。
小伙伴们注意,参数类型下面的query表示参数以key/value的形式传递,这里的值也可能是body,body表示参数以请求体的方式传递,例如上文的更新接口,如下:
当然还有一种可能就是这里的参数为path,表示参数放在路径中传递,例如根据id查询用户的接口:
三、把Swagger2的API接口导入到Postman中
1、访问http://localhost:8080/swagger-ui.html 文档的首页,复制下面这个地址:
2、打开postman->import–>import Form Link
四、Swagger2注解详解
1、@Api :请求类的说明
@Api:放在请求的类上,与 @Controller 并列,说明类的作用,如用户模块,订单类等。
tags="说明该类的作用"
value="该参数没什么意义,所以不需要配置"
举例
@RestController
@RequestMapping("/user")
@Api(tags = "用户控制器")
public class UserController {
//todo
}
2、@ApiOperation:方法的说明
@ApiOperation:"用在请求的方法上,说明方法的作用"
value="说明方法的作用"
notes="方法的备注说明"
举例
@GetMapping("/list")
@ApiOperation("用户列表接口")
public Result<User> list(){
//TODO
}
3、@ApiImplicitParams、@ApiImplicitParam:方法参数的说明
@ApiImplicitParams:用在请求的方法上,包含一组参数说明
@ApiImplicitParam:对单个参数的说明
name:参数名
value:参数的汉字说明、解释
required:参数是否必须传
paramType:参数放在哪个地方
· header --> 请求参数的获取:@RequestHeader
· query --> 请求参数的获取:@RequestParam
· path(用于restful接口)--> 请求参数的获取:@PathVariable
· body(请求体)--> @RequestBody User user
· form(普通表单提交)
dataType:参数类型,默认String,其它值dataType="int"
defaultValue:参数的默认值
举例
@PostMapping("/edit")
@ApiOperation(value = "用户修改接口",notes = "根据用户id修改用户名和密码",code = 0)
@ApiImplicitParams({
@ApiImplicitParam(name = "id",value = "用户id",required = true,dataType = "int"),
@ApiImplicitParam(name = "username",value = "用户名",required = true,dataType = "string"),
@ApiImplicitParam(name = "password",value = "用户密码",required = true,dataType = "string")
})
public boolean updateUser(@RequestParam("id")int id,@RequestParam("username") String username,@RequestParam("password") String password){
return false;
}
4、单个参数举例:
@ApiOperation("根据Id删除")
@ApiImplicitParam(name="userId",value="用户id",required=true,paramType="query")
@GetMapping("/delete")
public AjaxResult delete(String userId) {
//TODO
}
5、@ApiResponses、@ApiResponse:方法返回值的说明
@ApiResponses:方法返回对象的说明
@ApiResponse:每个参数的说明
code:数字,例如400
message:信息,例如"请求参数没填好"
response:抛出异常的类
举例
@ApiOperation(value = "修改密码", notes = "方法的备注说明,如果有可以写在这里")
@ApiResponses({
@ApiResponse(code = 400, message = "请求参数没填好"),
@ApiResponse(code = 404, message = "请求路径找不到")
})
@PostMapping("/changepass")
public AjaxResult changePassword(@AutosetParam SessionInfo sessionInfo,
@RequestBody @Valid PasswordModel passwordModel) {
//TODO
}
6、@ApiModel:用于JavaBean上面,表示一个JavaBean
@ApiModel:用于JavaBean的类上面,表示此 JavaBean 整体的信息
(这种一般用在post创建的时候,使用 @RequestBody 这样的场景,请求参数无法使用 @ApiImplicitParam 注解进行描述的时候 )
7、@ApiModelProperty:用在JavaBean的属性上面,说明属性的含义
@ApiModel("修改密码所需参数封装类")
public class PasswordModel
{
@ApiModelProperty("账户Id")
private String accountId;
//TODO
}
五、总结
配置好Swagger2并适当添加注解后,启动SpringBoot应用,访问http://localhost:8080/swagger-ui.html 即可浏览API文档。另外,我们需要为了API文档的可读性,适当的使用以上几种注解就可以。
源码已上传,地址:https://gitee.com/quiet_spring/SpringBoot-Swagger2.git
以上内容已发布至“服务端技术精选”公众号,搜索关注,共同交流