likes
comments
collection
share

SpringBoot2.x系列教程53--SpringBoot中整合Swagger在线文档接口

作者站长头像
站长
· 阅读数 17

前言

我们现在开发时,都是前后端一起配合工作的。后端团队实现项目中的核心业务,并向前端提供Web接口;前端团队调用这些Web接口,进行数据的渲染展示。但在这个过程中,就会存在一个问题。你可能会很好奇,Web接口是后端团队开发定义的,前端团队怎么知道这些接口的用法及注意事项呢?总不能每个接口,都需要后端人员讲给前端人员听吧?

其实这个是没有必要的,我们后端可以在定义接口时,就生成该Web接口对应的在线接口文档,前端团队就可以直接看到了。

那现在该用什么来生成这个Web接口文档呢?壹哥告诉你,我们可以使用Swagger来实现哦!那什么是Swagger,Swagger怎么用,请看这篇文章吧,壹哥 都有详细的讲解。

一. Swagger2简介

我们可以利用Spring Boot构建RESTful API,其目的通常都是由于多终端的原因。这些终端会共用很多底层业务逻辑,因此我们会抽象出这样的一层,来同时服务于多个移动端或者Web前端。

那么此时我们的RESTful API就有可能要面对多个开发人员或多个开发团队:IOS开发、Android开发或是Web开发等,为了减少与其他团队平时开发期间的频繁沟通成本,传统的做法是创建一份RESTful API文档来记录所有的接口细节。然而这样的做法有以下几个问题:

1️⃣.由于接口众多,并且细节复杂(需要考虑不同的HTTP请求类型、HTTP头部信息、HTTP请求内容等),高质量地创建这份文档本身就是件非常吃力的事;

2️⃣.随着时间推移,不断修改接口实现的时候都必须同步修改接口文档,而文档与代码又处于两个不同的媒介,除非有严格的管理机制,不然很容易导致不一致现象.

为了解决上面的问题,我们可以利用Swagger2,它可以轻松的整合到Spring Boot中,并与Spring MVC程序配合组织出强大RESTful API文档。它既可以减少我们创建文档的工作量,又可以将说明内容整合到实现代码中,让维护文档和修改代码整合为一体,可以让我们在修改代码逻辑的同时方便的修改文档说明。

另外Swagger2也提供了强大的页面测试功能来调试每个RESTful API,具体效果如下图所示:

SpringBoot2.x系列教程53--SpringBoot中整合Swagger在线文档接口

二. Swagger2具体实现

1. 创建一个新的web模块--demo49_swagger2

SpringBoot2.x系列教程53--SpringBoot中整合Swagger在线文档接口

2. 在pom文件中添加依赖

新增swagger2的依赖包:spring-fox。

<dependencies>
    <!--web启动器是与SpringMVC相关的依赖-->
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
    </dependency>

    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-test</artifactId>
        <scope>test</scope>
    </dependency>
  
    <!--springfox的核心jar包-->
    <dependency>
        <groupId>io.springfox</groupId>
        <artifactId>springfox-swagger2</artifactId>
        <version>2.7.0</version>
    </dependency>
    
    <!--springfox-ui的jar包(里面包含了swagger的界面静态文件)-->
    <dependency>
        <groupId>io.springfox</groupId>
        <artifactId>springfox-swagger-ui</artifactId>
        <version>2.7.0</version>
    </dependency>  
</dependencies>

3. 创建SwaggerConfig配置类

创建一个单独的package,新建一个SwaggerConfig类。

package com.yyg.boot.config;

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.RequestHandlerSelectors;
import springfox.documentation.service.ApiInfo;
import springfox.documentation.service.Contact;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2;

/**
 * @Author 一一哥Sun
 * @Date Created in 2020/5/13
 * @Description Description
 */
@Configuration
@EnableSwagger2
//@ComponentScan(basePackages = "com.yyg.boot.web")
public class Swagger2Config {

    @Bean
    public Docket api() {
        return new Docket(DocumentationType.SWAGGER_2)
                .select()
                .apis(RequestHandlerSelectors.any())
                .apis(RequestHandlerSelectors.basePackage("com.yyg.boot.web"))
                //.paths(PathSelectors.any())
                .build()
                .apiInfo(apiInfo());
    }

    private ApiInfo apiInfo() {
        return new ApiInfoBuilder()
                .title("XXX项目接口文档")
                .description("XXX项目接口测试")
                .version("1.0.1")
                .contact(new Contact("一一哥","https://yiyige.blog.csdn.net/","2312119590"))
                .termsOfServiceUrl("")
                .license("")
                .licenseUrl("")
                .build();
    }

}

4. 常用API说明

1️⃣.* 通过@Configuration注解,使得该类成为配置类,Spring可以加载该配置;*

2️⃣.* 再通过@EnableSwagger2注解来启用Swagger2;*

3️⃣. 通过createRestApi()方法创建Docket的Bean之后,apiInfo()方法用来创建该Api的基本信息(这些基本信息会展现在文档页面中)。 select()方法返回一ApiSelectorBuilder实例,用来控制哪些接口暴露给 Swagger来展现.

4️⃣. 为了增强用户友好性,我们通常需要自己增加一些说明来丰富文档内容.如下所示,我们通过@ApiOperation注解来给API增加说明、通过@ApiImplicitParams、@ApiImplicitParam注解来给参数增加说明。

5. 创建User实体类

package com.yyg.boot.domain;

import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;

import java.io.Serializable;

/**
 * @Author 一一哥Sun
 * @Date Created in 2020/5/13
 * @Description Description
 */
@Data
@ApiModel
public class User implements Serializable {

    @ApiModelProperty("用户id")
    private Long id;

    @ApiModelProperty("用户姓名")
    private String name;

    @ApiModelProperty("用户年龄")
    private Integer age;

}

6. 创建Controller

这里我们一个创建Controller,在里面定义一下接口方法,并在类和方法上添加Swagger的相关注解。

package com.syc.boot.web;

import com.syc.boot.domain.User;
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
// 通过这里配置使下面的映射都在/users下
@RequestMapping(value="/users")
public class UserController {

    // 创建线程安全的Map
    static Map<Long, User> users = Collections.synchronizedMap(new HashMap<>());

    // 处理GET请求,用来获取用户列表.
    // 可以通过@RequestParam获取从页面中传递进来的查询条件或者翻页信息等参数.
    @ApiOperation(value="获取用户列表", notes="")
    @RequestMapping(value="/", method=RequestMethod.GET)
    public List<User> getUserList() {
        return new ArrayList<>(users.values());
    }

    // 处理POST请求,用来创建User.
    // 除了@ModelAttribute绑定参数之外,还可以通过@RequestParam从页面中传递参数.
    @ApiOperation(value="创建用户", notes="根据User对象创建用户")
    @ApiImplicitParam(name = "user", value = "用户详细实体user", required = true, dataType = "User")
    @RequestMapping(value="/", method=RequestMethod.POST)
    public String addUser(@RequestBody User user) {
        users.put(user.getId(), user);
        System.out.println("user==="+users.get(user.getId()));
        return "success";
    }

    // 处理GET请求,用来获取url中id值的User信息;
    // url中的id可通过@PathVariable绑定到函数的参数中.
    @ApiOperation(value="获取用户详细信息", notes="根据url的id来获取用户详细信息")
    @ApiImplicitParam(name = "id", value = "用户ID", required = true, dataType = "Long")
    @RequestMapping(value="/{id}", method=RequestMethod.GET)
    public User getUser(@PathVariable Long id) {
        return users.get(id);
    }

    // 处理PUT请求,用来更新User信息.
    @ApiOperation(value="更新用户详细信息", notes="根据url的id来指定更新对象,并根据传过来的user信息来更新用户详细信息")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "用户ID", required = true, dataType = "Long"),
            @ApiImplicitParam(name = "user", value = "用户详细实体user", required = true, dataType = "User")
    })
    @RequestMapping(value="/{id}", method=RequestMethod.PUT)
    public String updateUser(@PathVariable Long id, @RequestBody User user) {
        User u = users.get(id);
        u.setName(user.getName());
        u.setAge(user.getAge());
        users.put(id, u);
        return "success";
    }

    // 处理DELETE请求,用来删除User
    @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";
    }
}

7. 创建入口类

package com.yyg.boot;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

/**
 * @Author 一一哥Sun
 * @Date Created in 2020/5/13
 * @Description Description
 */
@SpringBootApplication
public class RestfulApplication {

    public static void main(String[] args){
        SpringApplication.run(RestfulApplication.class,args);
    }

}

三. 功能测试

访问地址:[项目访问地址]/swagger-ui.html

例如: http://localhost:8080/swagger-ui.html

SpringBoot2.x系列教程53--SpringBoot中整合Swagger在线文档接口

这里也可以像postman那样进行简单的接口测试。 SpringBoot2.x系列教程53--SpringBoot中整合Swagger在线文档接口

结语

通过以上很简单的一些注解,我们就学会了如何生成在线接口文档了,这样我们再也不用费力的给前端人员讲解Web接口的用法了。顺便问大家一个问题,你觉得在企业里面,是前端人员的地位高,还是后端人员的地位高呢?请在评论区给壹哥留言,说说你的看法吧。

转载自:https://juejin.cn/post/7177878762917691453
评论
请登录