SpringBoot学习笔记(八)

本文主要介绍SpringBoot集成Swagger

  • 学习目标:

1.了解Swagger的概念及作用

2.掌握在项目中集成Swagger自动生成API文档

  • Swagger

Swagger 是一个规范和完整的框架,用于生成、描述、调用和可视化 RESTful 风格的 Web 服务。

使客户端和文件系统作为服务器以同样的速度来更新。文件的方法、参数和模型紧密集成到服务器端的代码,允许 API 来始终保持同步。Swagger 让部署管理和使用功能强大的 API 从未如此简单。

Swagger 官网

image

  • Swagger解决的问题

1.前后端通过API进行交互
2.前后端相对独立且松耦合
3.直接运行,在线测试API
3.支持多种语言(Java、Php等)

  • SpringBoot集成Swagger

要求:jdk 1.8 + 否则swagger2无法运行

springfox 需要两个jar包:

Springfox Swagger UI
Springfox Swagger2

Swagger UI

image

Swagger2

image

1.新建一个 SpringBoot-web 项目:

image

image

2.添加Maven依赖:(注意:这里有个大坑!!!

<!-- 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>
<!-- https://mvnrepository.com/artifact/io.springfox/springfox-swagger2 -->
<dependency>
	<groupId>io.springfox</groupId>
	<artifactId>springfox-swagger2</artifactId>
	<version>3.0.0</version>
</dependency>

3、编写 HelloConfig,测试确保可以运行

package com.zhou.config;

import org.springframework.context.annotation.Configuration;
import springfox.documentation.swagger2.annotations.EnableSwagger2;

@Configuration //配置类
@EnableSwagger2 //开启Swagger2的自动配置
public class SwaggerConfig {
}

4:Run 访问: http://localhost:8081/swagger-ui.html

image

出错:无法访问,本人查看网上的大部分资料,尝试了很多方法。都不行。最后降了pom依赖中的版本号,即上面我标注大坑的地方(导入依赖,我都用最新的,这次排错也没想到这里,耽误好多时间)

降低依赖版本:

image

<!-- https://mvnrepository.com/artifact/io.springfox/springfox-swagger2 -->
<dependency>
	<groupId>io.springfox</groupId>
	<artifactId>springfox-swagger2</artifactId>
	<version>2.9.2</version>
</dependency>
<!-- https://mvnrepository.com/artifact/io.springfox/springfox-swagger-ui -->
<dependency>
	<groupId>io.springfox</groupId>
	<artifactId>springfox-swagger-ui</artifactId>
	<version>2.9.2</version>
</dependency>

5.Run 再次访问:http://localhost:8081/swagger-ui.html

image

  • 配置Swagger
    1、Swagger实例Bean是Docket,所以通过配置Docket实例来配置Swaggger
    2.可以通过apiInfo()属性配置文档信息
    3.Docket 实例关联上 apiInfo()

image

package com.zhou.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
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;

import java.util.ArrayList;

@Configuration //配置类
@EnableSwagger2 //开启Swagger2的自动配置
public class SwaggerConfig {
    @Bean //配置docket 以及配置Swagger具体参数
    public Docket docket(){
        return new Docket(DocumentationType.SWAGGER_2).apiInfo(apiInfo()); //实例关联上 apiInfo()
    }

    private ApiInfo apiInfo(){
        Contact contact = new Contact("联系人的名字", "http://xxx.xxx.com/联系人访问连接", "联系人邮箱");
        return  new ApiInfo(
                "Hello Swagger", //标题
                "Swagger 该如何配置呢?", //描述
                "v1.0", //版本
                "http://terms.service.url/组织连接",//组织连接
                contact, //联系人信息
                "Apach 2.0 许可", //许可
                "许可连接", //许可连接
                new ArrayList<>() //扩展
        );
    }
}

4.Run 再次访问:http://localhost:8081/swagger-ui.html

image

  • 配置扫描

1.编写一个简单的Controller,HelloController类

package com.zhou.controller;

import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class HelloController {

    @GetMapping("/hello")
    public  String hello(){
        return "hello swagger";
    }
}

2、构建Docket时通过select()方法配置怎么扫描接口

    @Bean //配置docket 以及配置Swagger具体参数
    public Docket docket(){
        return new Docket(DocumentationType.SWAGGER_2)
                .apiInfo(apiInfo())//实例关联上 apiInfo()
                .select()
                .apis(RequestHandlerSelectors.basePackage("com.zhou.controller"))//扫描
                .build();
    }

3.重启 访问:http://localhost:8081/swagger-ui.html

image

随便看看:

image

4.除了通过包路径配置扫描接口外,还可以通过配置其他方式扫描接口:

any() // 扫描所有,项目中的所有接口都会被扫描到
none() // 不扫描接口
regex(final String pathRegex) // 通过正则表达式控制
ant(final String antPattern) // 通过ant()控制
// 通过方法上的注解扫描,如withMethodAnnotation(GetMapping.class)只扫描get请求
withMethodAnnotation(final Class<? extends Annotation> annotation)
// 通过类上的注解扫描,如.withClassAnnotation(Controller.class)只扫描有controller注解的类中的接口
withClassAnnotation(final Class<? extends Annotation> annotation)
basePackage(final String basePackage) // 根据包路径扫描接口

5.还可以配置接口扫描过滤:

public Docket docket() {
    return new Docket(DocumentationType.SWAGGER_2)
        .apiInfo(apiInfo())
        .select()
        .apis(RequestHandlerSelectors.basePackage("com.zhou.swagger.controller"))
        // 配置如何通过path过滤,即这里只扫描请求以/zhou开头的接口
        .paths(PathSelectors.ant("/zhou/**"))
        .build();
}
  • 配置Swagger开关

1、通过enable()方法配置是否启用swagger,如果是false,swagger将不能在浏览器中访问了

@Bean
public Docket docket() {
    return new Docket(DocumentationType.SWAGGER_2)
        .apiInfo(apiInfo())
        .enable(false)
        .select()
        .apis(RequestHandlerSelectors.basePackage("com.zhou.swagger.controller"))
        .paths(PathSelectors.ant("/zhou/**"))
        .build();
}

2、如何动态配置当项目处于test、dev环境时显示swagger,处于prod时不显示?

@Bean
public Docket docket(Environment environment) {
    // 设置要显示swagger的环境
    Profiles of = Profiles.of("dev", "test");
    // 判断当前是否处于该环境
    // 通过 enable() 接收此参数判断是否要显示
    boolean b = environment.acceptsProfiles(of);

    return new Docket(DocumentationType.SWAGGER_2)
        .apiInfo(apiInfo())
        .enable(b) //配置是否启用Swagger,如果是false,在浏览器将无法访问
        .select()
        .apis(RequestHandlerSelectors.basePackage("com.zhou.swagger.controller"))

        .paths(PathSelectors.ant("/zhou/**"))
        .build();

3、在项目中增加一个dev的配置文件查看效果

  • 配置API分组

1、通过groupName()方法即可配置分组(如果没有配置分组,默认是default):

    @Bean //配置docket 以及配置Swagger具体参数
    public Docket docket(){
        return new Docket(DocumentationType.SWAGGER_2)
                .apiInfo(apiInfo())//实例关联上 apiInfo()
                .groupName("小王") //配置分组
                .select()
                .apis(RequestHandlerSelectors.basePackage("com.zhou.controller"))//扫描
                .build();
    }

2、重启项目查看分组

image

3、如何配置多个分组?配置多个分组只需要配置多个docket即可:

image

    @Bean //配置docket 以及配置Swagger具体参数
    public Docket docket(){
        return new Docket(DocumentationType.SWAGGER_2)
                .apiInfo(apiInfo())//实例关联上 apiInfo()
                .groupName("小王") //配置分组
                .select()
                .apis(RequestHandlerSelectors.basePackage("com.zhou.controller"))//扫描
                .build();
    }
    @Bean
    public Docket docket2(){
        return new Docket(DocumentationType.SWAGGER_2).groupName("小周"); //配置分组
    }
    @Bean
    public Docket docket3(){
        return new Docket(DocumentationType.SWAGGER_2).groupName("小李"); //配置分组
    }
    @Bean
    public Docket docket4(){
        return new Docket(DocumentationType.SWAGGER_2).groupName("小赵"); //配置分组
    }
  1. Run 查看

image

  • 实体配置

1、新建一个实体类

package com.zhou.pojo;

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

@ApiModel("用户实体")//为类添加注释
public class User {
    @ApiModelProperty("用户名")//为类属性添加注释
    public String name;
    @ApiModelProperty("用户密码")
    public String password;
}

2、只要这个实体在请求接口的返回值上(即使是泛型),都能映射到实体项中:

@GetMapping("/getUser")
public User getUser(){
	return new User();
}
  1. Run 测试:

image

注:并不是因为@ApiModel这个注解让实体显示在这里了,而是只要出现在接口方法的返回值上的实体都会显示在这里,而@ApiModel和@ApiModelProperty这两个注解只是为实体添加注释的。

  • Swagger 常用注解

Swagger的所有注解定义在io.swagger.annotations包下:

image

部分注解如下:

Swagger注解 简单说明
@Api(tags = "xxx模块说明") 作用在模块类上
@ApiOperation("xxx接口说明") 作用在接口方法上
@ApiModel("xxxPOJO说明") 作用在模型类上:如VO、BO
@ApiModelProperty(value = "xxx属性说明",hidden = true) 作用在类方法和属性上,hidden设置为true可以隐藏该属性
@ApiParam("xxx参数说明") 作用在参数、方法和字段上,类似@ApiModelProperty

比如:给请求的接口配置一些注释

    @ApiOperation("小王的接口")
    @GetMapping("/getName")
    public  String getName(@ApiParam("这个名字会被返回") String name){
        return name;
    }

image

相较于传统的Postman或Curl方式测试接口,使用swagger简直就是傻瓜式操作,不需要额外说明文档,而且更不容易出错,只需要录入数据然后点击Execute,如果再配合自动化框架,可以说基本就不需要人为操作了。

image

提示:在正式环境要记得关闭Swagger,一来出于安全考虑二来也可以节省运行时内存。

  • 拓展:其他皮肤

我们可以导入不同的包实现不同的皮肤定义:

1、默认的 访问 http://localhost:8080/swagger-ui.html (如上面演示的,我更改了端口号:8081)
依赖:

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

2、bootstrap-ui 访问 http://localhost:8080/doc.html (我更改了端口号:8081))
依赖:

<!-- 引入swagger-bootstrap-ui包 /doc.html-->
<dependency>
    <groupId>com.github.xiaoymin</groupId>
    <artifactId>swagger-bootstrap-ui</artifactId>
    <version>1.9.1</version>
</dependency>

image

3、mg-ui 访问 http://localhost:8080/document.html (我更改了端口号:8081)
依赖:

<!-- 引入swagger-ui-layer包 /document.html-->
<dependency>
    <groupId>com.zyplayer</groupId>
    <artifactId>swagger-mg-ui</artifactId>
    <version>1.0.6</version>
</dependency>

image

进入:
image

posted @ 2021-03-25 21:29  江河湖泊  阅读(141)  评论(0编辑  收藏  举报