一、背景
由于Spring Boot具备快速开发、便捷部署等特性,很大一部分Spring Boot的用户会用来构建RESTful API。RESTful API为后台与前台的交互提供了简洁的接口API,并且有利于减少与其他团队的沟通成本,通常情况下,我们会创建一份RESTful API文档来记录所有的接口细节,但是这样做存在以下几个问题:
- 由于接口众多,并且细节复杂(需要考虑不同的HTTP请求类型、HTTP头部信息、HTTP请求内容等),要高质量地创建这份文档事件非常吃力的事,抱怨声不绝于耳。
- 随着时间推移,不断修改接口实现的时候都必须同步修改接口文档,而文档与代码又处于两个不同的媒介,除非有严格的管理机制,不然很容易导致不一致现象。
Swagger2的出现就是为了解决上述问题,并且能够轻松的整合到我们的SpringBoot中去,它既可以减少我们创建文档的工作量,同时也能够说明内容,又可以整合到代码中去,让维护文档和修改代码整合为一体,可以让我们在修改代码逻辑的同时方便的修改文档说明。另外Swagger2页面提供了强大的页面测试功能来调试每个RESTful API,具体效果如下:
二、实现步骤
1、添加Swagger2依赖
在pom.xml中加入Swagger的依赖:
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger2</artifactId>
<version>2.2.2</version>
</dependency>
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger-ui</artifactId>
<version>2.2.2</version>
</dependency>
2、创建Swagger2配置类
该配置类要在SpringBoot启动类的同级目录下创建:
package com.example.demo;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
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;
@Configuration
@EnableSwagger2
@ComponentScan("com.test.controller")
public class Swagger2 {
@Bean
public Docket createRestApi() {
return new Docket(DocumentationType.SWAGGER_2) //创建Docket的Bean
.apiInfo(apiInfo()) //创建该Api的基本信息
.select() //返回一个ApiSelectorBuilder示例用来控制哪些接口 暴露给Swagger来展现
.apis(RequestHandlerSelectors.basePackage("com.test.controller")) //Swagger会扫描该包下所有Controller定义的Api,并产生文档内容(除了被@ApiIgnore标注的请求)
.paths(PathSelectors.any())
.build();
}
//创建该Api的基本信息,这些信息会展现在文档页面中
private ApiInfo apiInfo() {
return new ApiInfoBuilder()
.title("Spring Boot中使用Swagger2构建RESTful APIs")
.description("更过java相关的内容请关注:https://blog.youkuaiyun.com/hdn_kb")
.termsOfServiceUrl("https://blog.youkuaiyun.com/hdn_kb")
.contact("hdn")
.version("1.0")
.build();
}
}
注意:@ComponentScan("com.test.controller")扫描包。如果访问的页面中看不到接口信息,需要指定扫描包。
说明:
如上面的代码示例,通过@Configuration注解让Spring来加载该配置类,再通过@EnableSwagger2注解来启动Swagger2;
再通过createRestApi函数创建Docket的B额按,apiInfo()用来创建该API的基本信息(这些信息基本会展现在文档页面中),select()函数返回一个ApiSelectorBuilder实例用来控制哪些接口暴露给Swagger来展现,本例子采用指定扫描包路径来定义,Swagger会扫描该包下所有的Controller定义的API,并产生文档内容(除了被@ApiIgnore指定的请求)。
3、添加文档内容
在完成上述配置后,其实已经可以产生文档内容,但是这样的文档主要针对请求本身,而描述主要来源于函数等命名产生,对用户并不友好。如下所示:
我们通常需要自己增加一些说明来丰富文档的内容。如下所示,我们通过@ApiOperation注解来给API增加说明、通过@ApiImplicitParams、@ApiImplicitParam注解来给参数增加说明。
package com.test.controller;
import com.test.bean.UserBean;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.springframework.web.bind.annotation.*;
import java.util.*;
@RestController
@RequestMapping("/user")
public class UserController {
static Map<Long, UserBean> users = Collections.synchronizedMap(new HashMap<Long, UserBean>());
//处理"/user/"的GET请求,用来获取用户列表
@ApiOperation(value="获取用户列表",notes = "")
@RequestMapping(value="/",method = RequestMethod.GET)
public List<UserBean> getUserList() {
ArrayList<UserBean> list = new ArrayList<UserBean>(users.values());
return list;
}
//处理"/user/"的POST请求,用来创建UserBean
@ApiOperation(value="创建用户",notes = "根据UserBean对象创建用户")
@ApiImplicitParam(name = "user", value = "用户详细实体userBean", required = true, dataType = "UserBean")
@RequestMapping(value="/",method = RequestMethod.POST)
public String postUser(@ModelAttribute UserBean user){
users.put(user.getId(),user);
return "success";
}
//处理"/user/{id}"的PUT请求,用来更新UserBean的信息
@ApiOperation(value="更新用户信息",notes = "根据url的id来获取用户详细信息")
@ApiImplicitParams({
@ApiImplicitParam(name = "id", value = "用户ID", required = true, dataType = "Long"),
@ApiImplicitParam(name = "user", value = "用户详细实体userBean", required = true, dataType = "UserBean")
})
@RequestMapping(value="/{id}", method=RequestMethod.PUT)
public String putUser(@PathVariable Long id,@ModelAttribute UserBean user){
UserBean u = users.get(id);
u.setName(user.getName());
u.setAge(user.getAge());
users.put(id,u);
return "success";
}
// 处理"/users/{id}"的GET请求,用来获取url中id值的User信息
@ApiOperation(value="获取用户详细信息",notes = "根据url的id来获取用户详细信息")
@ApiImplicitParam(name = "id", value = "用户id", required = true, dataType = "Long")
@RequestMapping(value="/{id}", method=RequestMethod.GET)
public UserBean getUser(@PathVariable Long id) {
// url中的id可通过@PathVariable绑定到函数的参数中
return users.get(id);
}
//处理"/user/{id}"的DELETE请求,用来删除UserBean
@ApiOperation(value="删除用户", notes="根据url的id来指定删除对象")
@ApiImplicitParam(name = "id", value = "用户ID", required = true, dataType = "Long")
@RequestMapping(value="/{id}", method=RequestMethod.DELETE)
public String deleteUser(@PathVariable Long id){
users.remove(id);
return "success";
}
}
效果如下:
4、测试
完成上述代码添加配置之后,启动Spring Boot程序,访问:http://localhost:8080/swagger-ui.html,就能看到RESTful API的页面,我们可以点开具体的API请求,可以看到具体的信息(Notes、参数等):
以post为例: