在前后端分离开发中,为了减少与其他团队的沟通成本,一般构建一份 RESTful API 文档来描述所有的接口信息,但是这种做法有很大的弊端:
- 接口众多,编写 RESTful API 文档工作量巨大,因为 RESTful API 文档不仅要包含接口的基本信息,如接口地址、接口请求参数以及接口返回值等,还要包含 HTTP 请求类型、 HTTP 请求头、请求参数类型、返回值类型、所需权限等。
- 维护不方便,一旦接口发生变化,就要修改文档。
- 接口测试不方便,一般只能借助第三方工具(如 Postman )来测试。
Swagger 2 是一个开源软件框架,可以帮助开发人员设计、构建、记录和使用 RESTful Web 服务,它将代码和文档融为一体,可以完美解决上述问题,使开发人员将大部分精力集中到业务中,而不是繁杂琐碎的文档中。
整合步骤
添加 Swagger 2 相关依赖:
<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>
创建 Swagger 2 的配置类:
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.Contact;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2;
@Configuration
@EnableSwagger2
public class SwaggerConfig {
@Bean
Docket docket() {
return new Docket(DocumentationType.SWAGGER_2)
.select()
.apis(RequestHandlerSelectors.basePackage("xyz.ther.boot.controller"))
.paths(PathSelectors.any())
.build().apiInfo(new ApiInfoBuilder()
.description("示例接口文档")
.contact(new Contact("Ther", "https://github/siriusol", "admin@163.com"))
.version("v1.0")
.title("API测试文档")
.license("Apache2.0")
.licenseUrl("http://www.apache.org/licenses/LICENSE-2.0")
.build());
}
}
代码解释:
- 首先通过
@EnableSwagger2
注解开启 Swagger 2 ,然后最主要的是配置一个 Docket。 - 通过 apis 方法配置要扫描的 controller 位置,通过 paths 方法配置路径。
- 在 apiInfo 中构建文档的基本信息,例如描述、联系人信息、版本、标题等。
Swagger 2 配置完成后,接下来开发接口,代码如下:
实体类:
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
@ApiModel(value = "用户实体类", description = "用户信息描述类")
public class User {
@ApiModelProperty(value = "用户名")
private String username;
@ApiModelProperty(value = "用户地址")
private String address;
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
}
Controller 类:
import io.swagger.annotations.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import springfox.documentation.annotations.ApiIgnore;
@RestController
@Api(tags = "用户数据接口")
public class UserController {
@Autowired
UserService userService;
@ApiOperation(value = "查询用户", notes = "根据 id 查询用户")
@ApiImplicitParam(paramType = "path", name = "id", value = "用户 id", required = true)
@GetMapping("/user/{id}")
public String getUserById(@PathVariable Integer id) {
return "userId=" + id;
}
@ApiResponses({
@ApiResponse(code = 200, message ="删除成功"),
@ApiResponse(code = 500, message = "删除失败")})
@ApiOperation(value = "删除用户", notes = "通过 id 删除用户")
@DeleteMapping("/user/{id}")
public Integer deleteUserByid(@PathVariable Integer id) {
return id;
}
@ApiOperation(value = "添加用户", notes ="传入用户名和地址添加一个用户")
@ApiImplicitParams({
@ApiImplicitParam(paramType = "query", name = "username", value = "用户名", required = true, defaultValue = "Ther"),
@ApiImplicitParam(paramType = "query", name = "address", value = "用户地址", required = true, defaultValue = "China")})
@PostMapping("/user")
public String addUser(@RequestParam String username, @RequestParam String address) {
return username + ":" + address;
}
@ApiOperation(value = "修改用户", notes ="传入用户信息修改用户")
@PutMapping("/user")
public String updateUser(@RequestBody User user) {
return user.toString();
}
@GetMapping("/ignore")
@ApiIgnore
public void ignoreMethod() {}
}
代码解释:
- @Api 注解用在类上,用来描述整个 Controller 信息。
- @ApiOperation 注解用在方法上,用来描述一个方法的基本信息,value 是对方法作用的一个简短描述,notes 则用来备注该方法的详细作用。
- @ApilmplicitParam 注解用在方法上,用来描述方法的参数, paramType 是指方法参数的类型,可选值有 path (参数获取方式 @PathVariable)、query (参数获取方式 @RequestParam)、header (参数获取方式 RequestHeader)、body 以及 form;name 表示参数名称,和参数变量对应;value 是参数的描述信息; required 表示该字段是否必填; defaultValue 表示该字段的默认值。注意,这里的 required 和 defaultValue 等字段只是文档上的约束描述,并不能真正约束接口,约束接口还需要在 @RequestParam 中添加相关属性。如果方法有多个参数,可以将多个参数 @ApilmplicitParam 注解放到 @ApilmplicitParams 中。
- @ApiResponse 注解是对响应结果的描述,code 表示响应码,message 表示响应的描述信息, 若有多个 @ApiResponse,则放在一个 @ApiResponses 中。
- updateUser 方法中,使用 @RequestBody 注解来接收数据,此时可以通过 @ApiModel 注解和 @ApiModelProperty 注解配置 User 的描述信息。
- @Apilgnore 注解表示不对某个接口生成文档。
启动 Spring Boot 项目,在浏览器中输入:http://localhost:8080/swagger-ui.html 即可看到接口文档。