Spring Boot中使用Swagger2自动构建API文档

因为Spring Boot可以快速开发、便捷部署等特性,相信有很大一部分Spring Boot的用户会用来构建RESTful API。而咱们构建RESTful API的目的一般都是因为多终端的缘由,这些终端会共用不少底层业务逻辑,所以咱们会抽象出这样一层来同时服务于多个移动端或者Web前端。html

这样一来,咱们的RESTful API就有可能要面对多个开发人员或多个开发团队:IOS开发、Android开发或是Web开发等。为了减小与其余团队平时开发期间的频繁沟通成本,传统作法咱们会建立一份RESTful API文档来记录全部接口细节,然而这样的作法有如下几个问题:前端

  • 因为接口众多,而且细节复杂(须要考虑不一样的HTTP请求类型、HTTP头部信息、HTTP请求内容等),高质量地建立这份文档自己就是件很是吃力的事,下游的抱怨声不绝于耳。
  • 随着时间推移,不断修改接口实现的时候都必须同步修改接口文档,而文档与代码又处于两个不一样的媒介,除非有严格的管理机制,否则很容易致使不一致现象。

为了解决上面这样的问题,本文将介绍RESTful API的重磅好伙伴Swagger2,它能够轻松的整合到Spring Boot中,并与Spring MVC程序配合组织出强大RESTful API文档。它既能够减小咱们建立文档的工做量,同时说明内容又整合入实现代码中,让维护文档和修改代码整合为一体,可让咱们在修改代码逻辑的同时方便的修改文档说明。另外Swagger2也提供了强大的页面测试功能来调试每一个RESTful API。具体效果以下图所示:git

构建RESTful API

在使用Swagger2前咱们须要有一个RESTful API的项目. Spring-Boot建立RESTful API项目很是的方便和快速,这里再也不介绍如何建立github

添加Swagger2依赖

在pom.xml文件中加入如下依赖:web

<dependency>
        <groupId>io.springfox</groupId>
    <artifactId>springfox-swagger2</artifactId>
    <version>2.7.0</version>
</dependency>
<dependency>
        <groupId>io.springfox</groupId>
        <artifactId>springfox-swagger-ui</artifactId>
        <version>2.7.0</version>
</dependency>

建立Swagger2的Java配置类

经过@Configuration注解,代表它是一个配置类,@EnableSwagger2 注解开启swagger2。apiInfo() 方法配置一些基本的信息。createRestApi() 方法指定扫描的包会生成文档,默认是显示全部接口,能够用@ApiIgnore注解标识该接口不显示。spring

 1 @Configuration
 2 @EnableSwagger2
 3 public class Swagger2 {
 4 
 5     @Bean
 6     public Docket createRestApi() {
 7         return new Docket(DocumentationType.SWAGGER_2)
 8                 .apiInfo(apiInfo())
 9                 .select()
10                 .apis(RequestHandlerSelectors.basePackage("com.didispace.web"))
11                 .paths(PathSelectors.any())
12                 .build();
13     }
14 
15     private ApiInfo apiInfo() {
16         return new ApiInfoBuilder()
17                 .title("Spring Boot中使用Swagger2构建RESTful APIs")
18                 .description("更多Spring Boot相关文章请关注")
19                 .termsOfServiceUrl("http://blog.didispace.com/")
20                 .contact("程序猿")
21                 .version("1.0")
22                 .build();
23     }
24 
25 }

如上代码所示,经过@Configuration注解,让Spring来加载该类配置。再经过@EnableSwagger2注解来启用Swagger2。api

再经过createRestApi函数建立Docket的Bean以后,apiInfo()用来建立该Api的基本信息(这些基本信息会展示在文档页面中)。select()函数返回一个ApiSelectorBuilder实例用来控制哪些接口暴露给Swagger来展示,本例采用指定扫描的包路径来定义,Swagger会扫描该包下全部Controller定义的API,并产生文档内容(除了被@ApiIgnore指定的请求)。数据结构

添加文档内容

在完成了上述配置后,其实已经能够生产文档内容,可是这样的文档主要针对请求自己,而描述主要来源于函数等命名产生,对用户并不友好,咱们一般须要本身增长一些说明来丰富文档内容。以下所示,咱们经过@ApiOperation注解来给API增长说明、经过@ApiImplicitParams@ApiImplicitParam注解来给参数增长说明。app

 1 @RestController
 2 @RequestMapping(value="/users")     // 经过这里配置使下面的映射都在/users下,可去除
 3 public class UserController {
 4 
 5     static Map<Long, User> users = Collections.synchronizedMap(new HashMap<Long, User>());
 6 
 7     @ApiOperation(value="获取用户列表", notes="")
 8     @RequestMapping(value={""}, method=RequestMethod.GET)
 9     public List<User> getUserList() {
10         List<User> r = new ArrayList<User>(users.values());
11         return r;
12     }
13 
14     @ApiOperation(value="建立用户", notes="根据User对象建立用户")
15     @ApiImplicitParam(name = "user", value = "用户详细实体user", required = true, dataType = "User")
16     @RequestMapping(value="", method=RequestMethod.POST)
17     public String postUser(@RequestBody User user) {
18         users.put(user.getId(), user);
19         return "success";
20     }
21 
22     @ApiOperation(value="获取用户详细信息", notes="根据url的id来获取用户详细信息")
23     @ApiImplicitParam(name = "id", value = "用户ID", required = true, dataType = "Long")
24     @RequestMapping(value="/{id}", method=RequestMethod.GET)
25     public User getUser(@PathVariable Long id) {
26         return users.get(id);
27     }
28 
29     @ApiOperation(value="更新用户详细信息", notes="根据url的id来指定更新对象,并根据传过来的user信息来更新用户详细信息")
30     @ApiImplicitParams({
31             @ApiImplicitParam(name = "id", value = "用户ID", required = true, dataType = "Long"),
32             @ApiImplicitParam(name = "user", value = "用户详细实体user", required = true, dataType = "User")
33     })
34     @RequestMapping(value="/{id}", method=RequestMethod.PUT)
35     public String putUser(@PathVariable Long id, @RequestBody User user) {
36         User u = users.get(id);
37         u.setName(user.getName());
38         u.setAge(user.getAge());
39         users.put(id, u);
40         return "success";
41     }
42 
43     @ApiOperation(value="删除用户", notes="根据url的id来指定删除对象")
44     @ApiImplicitParam(name = "id", value = "用户ID", required = true, dataType = "Long")
45     @RequestMapping(value="/{id}", method=RequestMethod.DELETE)
46     public String deleteUser(@PathVariable Long id) {
47         users.remove(id);
48         return "success";
49     }
50 
51 }

完成上述代码添加上,启动Spring Boot程序,访问:http://localhost:8080/swagger-ui.html
。就能看到前文所展现的RESTful API的页面。咱们能够再点开具体的API请求,以POST类型的/users请求为例,可找到上述代码中咱们配置的Notes信息以及参数user的描述信息,以下图所示。函数

API文档访问与调试

在上图请求的页面中,咱们看到user的Value是个输入框?是的,Swagger除了查看接口功能外,还提供了调试测试功能,咱们能够点击上图中右侧的Model Schema(黄色区域:它指明了User的数据结构),此时Value中就有了user对象的模板,咱们只须要稍适修改,点击下方“Try it out!”按钮,便可完成了一次请求调用!

此时,你也能够经过几个GET请求来验证以前的POST请求是否正确。

相比为这些接口编写文档的工做,咱们增长的配置内容是很是少并且精简的,对于原有代码的侵入也在忍受范围以内。所以,在构建RESTful API的同时,加入swagger来对API文档进行管理,是个不错的选择。

Annotation使用详解

@ApiOperation:用在方法上,说明方法的做用

  • value: 表示接口名称
  • notes: 表示接口详细描述

@ApiImplicitParams用在方法上包含一组参数说明

@ApiImplicitParam用在@apiimplicitparams注解中,指定一个请求参数的各个方面

  • paramType:参数位置
  • header 对应注解:@requestheader
  • query 对应注解:@requestparam
  • path 对应注解: @pathvariable
  • body 对应注解: @requestbody
  • name:参数名
  • dataType:参数类型
  • required:参数是否必须传
  • value:参数的描述
  • defaultValue:参数的默认值

@ApiResponses:用于表示一组响应

@ApiResponse用在@apiresponses中,通常用于表达一个错误的响应信息

  • code:状态码

  • message:返回自定义信息

  • response:抛出异常的类

@ApiModel

描述一个Model的信息(这种通常用在post建立的时候,使用@RequestBody这样的场景,请求参数没法使用@ApiImplicitParam注解进行描述的时候)
@ApiModel(value = "用户实体类")

 @ApiModelProperty

描述一个model的属性
@ApiModelProperty(value = "登陆用户")

 

附:

 1      <dependency>
 2             <groupId>io.springfox</groupId>
 3             <artifactId>springfox-swagger2</artifactId>
 4             <version>2.9.2</version>
 5             <!-- 解决 io.swagger.models.parameters.AbstractSerializableParameter.getExample @ApiModelProperty example 必须为数字的问题 -->
 6             <exclusions>
 7                 <exclusion>
 8                     <groupId>io.swagger</groupId>
 9                     <artifactId>swagger-annotations</artifactId>
10                 </exclusion>
11                 <exclusion>
12                     <groupId>io.swagger</groupId>
13                     <artifactId>swagger-models</artifactId>
14                 </exclusion>
15             </exclusions>
16         </dependency>
17         <dependency>
18             <groupId>io.swagger</groupId>
19             <artifactId>swagger-annotations</artifactId>
20             <version>1.5.21</version>
21         </dependency>
22         <dependency>
23             <groupId>io.swagger</groupId>
24             <artifactId>swagger-models</artifactId>
25             <version>1.5.21</version>
26         </dependency>
27         <dependency>
28             <groupId>io.springfox</groupId>
29             <artifactId>springfox-swagger-ui</artifactId>
30             <version>2.9.2</version>
31         </dependency>

 

参考资料:http://www.javashuo.com/article/p-xqhgagch-mb.html

相关文章
相关标签/搜索