Swagger的配置与使用

问题:前后端分离时代的到来

  • 前端需要测试后端数据

  • 后端提供接口,实时更新接口的改动

一、Swagger简介

  • 号称世界上最流行的api框架

  • Restful api文档在线自动生成工具–>api文档与api定义同步更新

  • 直接运行,可以在线测试api接口

  • 支持多种语言(java、php)

官网:https://swagger.io/

在项目中使用swagger需要springfox jar包

  • swagger2
  • swagger ui

二、springboot集成swagger

  1. 新建springboot项目

  2. 导入jar包

    <!--swaggerjar包-->
    <dependency>
        <groupId>io.springfox</groupId>
        <artifactId>springfox-swagger-ui</artifactId>
        <version>2.9.2</version>
    </dependency>
    <dependency>
        <groupId>io.springfox</groupId>
        <artifactId>springfox-swagger2</artifactId>
        <version>2.9.2</version>
    </dependency>
    
  3. 编写一个helloworld

    package com.kj.controller;
    
    import org.springframework.web.bind.annotation.RequestMapping;
    import org.springframework.web.bind.annotation.RestController;
    
    @RestController
    public class SwaggerController {
    
        @RequestMapping("/hello")
        public String hello(){
            return "hello";
        }
    }
    
  4. 配置swagger

    import org.springframework.context.annotation.Configuration;
    import springfox.documentation.swagger2.annotations.EnableSwagger2;
    
    @Configuration
    @EnableSwagger2 //开启swagger
    public class SwaggerConfig {
    
    }
    

    启动类加上@EnableSwagger2注解(遇到Unable to infer base url.bug时加入,可以解决)

    package com.kj;
    
    import org.springframework.boot.SpringApplication;
    import org.springframework.boot.autoconfigure.SpringBootApplication;
    import springfox.documentation.swagger2.annotations.EnableSwagger2;
    
    @SpringBootApplication
    @EnableSwagger2
    public class SwaggerDemoApplication {
    
        public static void main(String[] args) {
            SpringApplication.run(SwaggerDemoApplication.class, args);
        }
    
    }
    
  5. 启动运行

    访问localhost/swagger-ui.html。没有配置port的是这个地址localhost:8080/swagger-ui.html

    swagger-ui.html所在文件
    在这里插入图片描述
    在这里插入图片描述

三、配置swagger

1、配置ApiInfo

swagger需要一个docket实例

可以看到docket的构造函数,需要一个DocumentationType

public Docket(DocumentationType documentationType) {
    this.apiInfo = ApiInfo.DEFAULT;
    this.groupName = "default";
    this.enabled = true;
    this.genericsNamingStrategy = new DefaultGenericTypeNamingStrategy();
    this.applyDefaultResponseMessages = true;
    this.host = "";
    this.pathMapping = Optional.absent();
    this.apiSelector = ApiSelector.DEFAULT;
    this.enableUrlTemplating = false;
    this.vendorExtensions = Lists.newArrayList();
    this.documentationType = documentationType;
}

而DocumentationType有三个默认的值

public class DocumentationType extends SimplePluginMetadata {
    public static final DocumentationType SWAGGER_12 = new DocumentationType("swagger", "1.2");
    public static final DocumentationType SWAGGER_2 = new DocumentationType("swagger", "2.0");
    public static final DocumentationType SPRING_WEB = new DocumentationType("spring-web", "1.0");
    
......
    
}

所以我们可以这样向容器中创建一个docket

@Bean
public Docket docket(){
    return new Docket(DocumentationType.SWAGGER_2);
}

此时改配置信息,调用docket的函数即可。

比如修改swagger的api信息,我们需要更改ApiInfo
在这里插入图片描述

相关源码

public Docket(DocumentationType documentationType) {
    this.apiInfo = ApiInfo.DEFAULT; //api描述
    this.groupName = "default";
    this.enabled = true;
    this.genericsNamingStrategy = new DefaultGenericTypeNamingStrategy();
    this.applyDefaultResponseMessages = true;
    this.host = "";
    this.pathMapping = Optional.absent();
    this.apiSelector = ApiSelector.DEFAULT;
    this.enableUrlTemplating = false;
    this.vendorExtensions = Lists.newArrayList();
    this.documentationType = documentationType;
}

//默认的apiInfo
static {
    DEFAULT = new ApiInfo("Api Documentation",
                          "Api Documentation",
                          "1.0", "urn:tos",
                          DEFAULT_CONTACT,
                          "Apache 2.0",
                          "http://www.apache.org/licenses/LICENSE-2.0",
                          new ArrayList());
}

//作者信息
public static final Contact DEFAULT_CONTACT = new Contact("", "", "");

这时候为我们自己的docket注入咱们自己的apiInfo即可

@Bean
public Docket docket(){
return new Docket(DocumentationType.SWAGGER_2).apiInfo(getApiInfo());
}

private static ApiInfo getApiInfo(){
return new ApiInfo("KJ Api文件",
"swagger测试",
"1.0",
"https://blog.csdn.net/KJ_Study",
new Contact("KJ", "https://blog.csdn.net/KJ_Study", "qi1638629056@163.com"),
"Apache 2.0",
"http://www.apache.org/licenses/LICENSE-2.0",
new ArrayList());
}

结果如下(其实这个基本没任何效率上的作用)

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-BwmxUArS-1603805413095)(D:\java\myNote\image\00.png)]

2、配置扫描接口

有一个方法Docket.select()

@Bean
public Docket docket(){
    return new Docket(DocumentationType.SWAGGER_2).apiInfo(getApiInfo())
            .select()
            .build();
}

只能build两个方法apis与paths

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-1J666Gso-1603805413097)(D:\java\myNote\image\812217.png)]

配置扫描目标

有扫描全部any,一个都不扫描none,基于包扫描basePackage,通过方法注解扫描(扫描有这个注解的方法,可以自己加入GetMapper.class的参数),通过类注解扫描

用的多的还是basePackage

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-AB4tC2n6-1603805413098)(D:\java\myNote\image\016579.png)]

我们指定一个扫描包

@Bean
public Docket docket(){
    return new Docket(DocumentationType.SWAGGER_2).apiInfo(getApiInfo())
        .select()
        .apis(RequestHandlerSelectors.basePackage("com.kj.controller")) //RequestHandlerSelectors配置扫描接口的方式
        .build();
}

结果

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-ofGBSf7x-1603805413099)(D:\java\myNote\image\7201240619.png)]

3、过滤路径

扫描带有/kj/ url的api,我们只有一个/hello请求,所以不会有任何api

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

4、配置是否启用swagger

将docket的enabled属性改为false即可

//docket的部分源码
public Docket(DocumentationType documentationType) {
    this.apiInfo = ApiInfo.DEFAULT;
    this.groupName = "default";
    this.enabled = true; //是否使用swagger
    this.genericsNamingStrategy = new DefaultGenericTypeNamingStrategy();
    this.applyDefaultResponseMessages = true;
    this.host = "";
    this.pathMapping = Optional.absent();
    this.apiSelector = ApiSelector.DEFAULT;
    this.enableUrlTemplating = false;
    this.vendorExtensions = Lists.newArrayList();
    this.documentationType = documentationType;
}

public Docket enable(boolean externallyConfiguredFlag) {
    this.enabled = externallyConfiguredFlag;
    return this;
}

所以我们enable一下

@Bean
public Docket docket(){
    return new Docket(DocumentationType.SWAGGER_2).apiInfo(getApiInfo())
            .select()
            .apis(RequestHandlerSelectors.basePackage("com.kj.controller")) //RequestHandlerSelectors配置扫描接口的方式
            .build()
            .enable(false);
}

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-jWng4qK8-1603805413100)(D:\java\myNote\image\535525.png)]

实际使用:我们通过外部的环境来判断是否调用swagger

@Bean
public Docket docket(Environment environment){
    //设置显示要调用swagger的环境,可以有多个值
    Profiles profiles = Profiles.of("dev");
    //判断当前的环境与指定的是否一样
    boolean flag = environment.acceptsProfiles(profiles);

    return new Docket(DocumentationType.SWAGGER_2).apiInfo(getApiInfo())
            .select()
            .apis(RequestHandlerSelectors.basePackage("com.kj.controller")) //RequestHandlerSelectors配置扫描接口的方式
            .build()
            .enable(flag);
}

我们有多个配置文件,一个用于开发,一个用于部署

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-e4mB3D9B-1603805413101)(D:\java\myNote\image\319216.png)]

5、配置api文档的分组

主要的是groupName

public Docket(DocumentationType documentationType) {
    this.apiInfo = ApiInfo.DEFAULT;
    this.groupName = "default";
    this.enabled = true;
    this.genericsNamingStrategy = new DefaultGenericTypeNamingStrategy();
    this.applyDefaultResponseMessages = true;
    this.host = "";
    this.pathMapping = Optional.absent();
    this.apiSelector = ApiSelector.DEFAULT;
    this.enableUrlTemplating = false;
    this.vendorExtensions = Lists.newArrayList();
    this.documentationType = documentationType;
}
@Bean
public Docket docket(Environment environment){
    Profiles profiles = Profiles.of("dev");
    boolean flag = environment.acceptsProfiles(profiles);

    return new Docket(DocumentationType.SWAGGER_2).apiInfo(getApiInfo())
            .select()
            .apis(RequestHandlerSelectors.basePackage("com.kj.controller"))
            .build()
            .enable(flag)
            .groupName("KJ");
}

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-bMU5MBRm-1603805413102)(D:\java\myNote\image\920.png)]

我们可以看到一个docket一个分组。要想要多个我们再创建几个docket即可。

注意组名不能相同,如果相同spring会报bug并结束进程

@Bean
public Docket docket1() {
    return new Docket(DocumentationType.SWAGGER_2).apiInfo(getApiInfo())
        .groupName("A");
}

@Bean
public Docket docket2() {
    return new Docket(DocumentationType.SWAGGER_2).apiInfo(getApiInfo())
        .groupName("B");
}

@Bean
public Docket docket3() {
    return new Docket(DocumentationType.SWAGGER_2).apiInfo(getApiInfo())
        .groupName("C");
}

不同后端开发人员选择自己的组,就可以只看到自己的api

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-foJEggcE-1603805413103)(D:\java\myNote\image\3072.png)]

6、实体类配置

只要返回值中存在,就会被swagger扫描

编写一个pojo

package com.kj.pojo;

public class User {
    private String username;
    private String password;
}

编写一个方法

@RestController
public class SwaggerController {

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

    @PostMapping("/user")
    public User user(){
        return new User();
    }
}

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-9RDP8v0R-1603805413104)(D:\java\myNote\image\725082.png)]

我们也可以在实体类加上注注释(在显示时,只显示注解配置的内容),显不显示与这个注解无关

package com.kj.pojo;

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

@ApiModel("实体类")
public class User {
    @ApiModelProperty("用户名")
    public String username;
    @ApiModelProperty("密码")
    private String password;
}

可以看到私有方法是看不到的

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-Nxr5Vt9m-1603805413105)(D:\java\myNote\image\029103.png)]

同样我们也可以给方法加注释,或者给参数加注释

@RestController
public class SwaggerController {

    @ApiOperation("哈喽方法")
    @RequestMapping("/hello")
    public String hello(){
        return "hello";
    }

    @PostMapping("/user")
    public User user(){
        return new User();
    }
    
    @GetMapping("/hello2")
    public String hello2(@ApiParam("用户名") String name){
        return "hello";
    }
}

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-JXIoRVIH-1603805413106)(D:\java\myNote\image\image-20201027210524853.png)]

四、发送请求

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-g3DwlRzB-1603805413107)(D:\java\myNote\image\11419585.png)]

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-YRtaEi5V-1603805413107)(D:\java\myNote\image\448545.png)]

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-czRXnoIx-1603805413108)(D:\java\myNote\image\1511251.png)]

下面就可以看到结果了

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值