Swagger学习笔记

Swagger学习笔记

博主 963 2020-08-05

学习目标:

  • 了解Swagger的作用和概念
  • 了解前后端分离
  • 在SpringBoot中集成Swagger

1 谈谈前后端分离

前后端分离开发,需要定义接口,然而写代码的如果同时要去手动维护接口文档,十分繁琐,就有工具出来解决这个痛点,就是Swagger
web开发的历史:

  • 后端主导开发的时代:前端写静态页面,后端把业务逻辑和前端给的页面一起渲染,例如使用模板引擎,jsp
  • 前后端分离时代:
    -- 后端:后端分为MVC三层,控制层,业务层,持久层
    -- 前端:前端分为MVVM层(不知道我描述的对不对),视图层,数据层,数据视图层
    ---- 前端可以伪造后端数据,自己写json字符串,不需要后端就可以把项目跑起来

前后端分离以后,只能过API实现交互,相对独立,松散,耦合低。前后端可以部署在不同的服务器上。

  • 产生的问题:前后端集成联调,前后端人员无法做到“及时协商,及时解决”,可能会导致问题集中爆发
  • 解决方案
    -- 指定schema计划提纲,实时更新最新API,降低集成的风险
    -- 之前通过指定word计划文档的方式解决
    -- 前后端分离以后
    ---- 前端测试后端接口:postman
    ---- 后端提供接口,需要实时更新最新的消息及改动

此时Swagger应用而生,解决了这个痛点
Swagger是世界上最流行的API框架之一,提供一个RestFul Api文档在线自动生成工具
可以直接运行,在线测试API接口
支持多种语言:Java,PHP等

官网:https://swagger.io/

在项目中使用Swagger需要SpringBoot(Spring也可以)

  • Swagger2
  • UI

2 在SpringBoot项目中集成Swagger

  1. 新建一个SpringBoot项目
  2. pom.xml导包
<!-- https://mvnrepository.com/artifact/io.springfox/springfox-swagger2 -->
        <dependency>
            <groupId>io.springfox</groupId>
            <artifactId>springfox-swagger2</artifactId>
            <version>3.0.0</version>
        </dependency>

        <!-- https://mvnrepository.com/artifact/io.springfox/springfox-swagger-ui -->
        <dependency>
            <groupId>io.springfox</groupId>
            <artifactId>springfox-swagger-ui</artifactId>
            <version>3.0.0</version>
        </dependency>
  1. 编写一个控制器
@Controller
public class IndexController {

    @RequestMapping("/hello")
    @ResponseBody
    public String hello(){
        return "hello";
    }
}
  1. 创建配置类,集成Swagger
@Configuration
@EnableSwagger2 //开启Swagger2
public class SwaggerConfig {
}
  1. 测试访问
    测试访问 http://localhost:8080/swagger-ui.html
    然后就404了,淦!
    找了一下解决方案
    因为使用的是3.0版本,重新导入jar
<dependency>
            <groupId>io.springfox</groupId>
            <artifactId>springfox-boot-starter</artifactId>
            <version>3.0.0</version>
</dependency>

然后访问 http://localhost:8080/swagger-ui/index.html
image.png

  1. 配置Swagger
    通过Swagger的bean实例Docket配置
    先配置ApiInfo信息
@Bean
    public Docket getDocket() {
        return new Docket(DocumentationType.SWAGGER_2).apiInfo(apiInfo());
    }

    private ApiInfo apiInfo() {
        Contact contact = new Contact("无名高", "https://wuminggao.cn", "wuminggao594@foxmail.com");

        return new ApiInfo("Swagger接口文档",
                "我是一个描述", "1.0.0",
                "https://wuminggao.cn", contact,
                "Apache 2.0", "http://www.apache.org/licenses/LICENSE-2.0",
                new ArrayList());

    }

可以看到ui界面的变化
image.png

可以配置扫描接口的方式

@Bean
    public Docket getDocket() {
        return new Docket(DocumentationType.SWAGGER_2)
                .apiInfo(apiInfo())
                .select()
                //RequestHandlerSelectors 配置要扫描接口的方式
                // basePackage指定要扫描的包
                // any扫描全部
                // none不扫描
                // withClassAnnotation 扫描类上的注解,参数是一个注解的反射对象
                // withMethodAnnotation 扫描方法上的注解
                .apis(RequestHandlerSelectors.basePackage("com.learn.wuminggao.swaggerdemo.controller"))
                //过滤,要扫描的请求路径,此处为扫描/ww下的所有请求路径
                .paths(PathSelectors.ant("/hello/**"))
                .build()
                //是否启用Swagger
                .enable(false);
    }

Swagger在开发环境和测试环境使用,在发布的时候不使用
可以在生产环境的配置文件配置,

springfox:
  documentation:
    swagger-ui:
      enabled: false

可以通过Docket的groupName属性配置group分组信息
image.png
主要涉及协同开发的事情,不同group有自己的不同docket实例,可以在ui界面切换查看group

3 接口注释

通过@ApiModel设置类的信息, @ApiModelProperty设置字段的信息
注意如果字段是private修饰的,不会在model里面显示
此处有误,private属性通过设置get方法就可以显示了

在controller中返回一个model

/**
     * 只要返回值存在一个model,就会在ui看到model
     * @return
     */
    @PostMapping("/user")
    public User helloUser(){
        return new User();
    }

定义实体类

@ApiModel("用户实体类")
public class User {

    @ApiModelProperty("用户名")
    public String username;
    @ApiModelProperty("密码")
    public String password;

}

通过@ApiOperation给控制器方法加注释

@ApiOperation("Index控制器中的hello方法")
    @RequestMapping("/hello")
    public String hello(){
        return "hello";
    }

通过@ApiParam给参数添加注解

@PostMapping("/user")
    public User helloUser(@ApiParam("用户名") String username){
        return new User();
    }

通过@Api给Controller添加注释
@Api(tags = {"Index控制器"}) // tags是对Controller的接口重新分类
public class IndexController

通过这种方式,可以给一些难以理解的属性和接口,添加注释信息
接口文档实时更新
可以在线测试

测试接口

@PostMapping("/user")
    public User helloUser(@ApiParam(value = "用户名", example = "root") @RequestParam("username") String username,
                          @ApiParam(value = "密码", example = "root")@RequestParam("password") String password){
        return new User(username, password);
    }

image.png
得到json字符串
image.png