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

  • 前端需要测试后端数据

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

一、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());
}

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

2、配置扫描接口

有一个方法Docket.select()

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

只能build两个方法apis与paths

配置扫描目标

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

用的多的还是basePackage

我们指定一个扫描包

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

结果

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);
}

实际使用:我们通过外部的环境来判断是否调用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);
}

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

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");
}

我们可以看到一个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

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();
}
}

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

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;
}

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

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

@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";
}
}

四、发送请求





下面就可以看到结果了

Swagger配置与使用的更多相关文章

  1. 一、Swagger配置

    一.Swagger配置 1.注解不显示 SwaggerConfig文件下   //c.IncludeXmlComments(GetXmlCommentsPath()):  内下面添加: c.Inclu ...

  2. Spring Boot项目简单上手+swagger配置+项目发布(可能是史上最详细的)

    Spring Boot项目简单上手+swagger配置 1.项目实践 项目结构图 项目整体分为四部分:1.source code 2.sql-mapper 3.application.properti ...

  3. swagger配置

    1.pom.xml <!--swagger2--> <dependency> <groupId>io.springfox</groupId> <a ...

  4. swagger 配置- ssm

    swagger 配置 - ssm swagger 是一个用来看接口的工具,具体效果如下,这里用的是swagger2 1.porm.xml <dependency> <groupId& ...

  5. 尝试从零开始构建我的商城 (二) :使用JWT保护我们的信息安全,完善Swagger配置

    前言 GitHub地址 https://github.com/yingpanwang/MyShop/tree/dev_jwt 此文对应分支 dev_jwt 此文目的 上一篇文章中,我们使用Abp vN ...

  6. webapi Swagger 配置 services.BuildServiceProvider() 报警 ASP0000 问题处理

    问题起源 网上的常见配置 Swagger 配置 在Startup类的 ConfigureServices 使用 services.BuildServiceProvider() ,其中有段代码如下: v ...

  7. 《Asp.Net Core3 + Vue3入坑教程》-Net Core项目搭建与Swagger配置步骤

    简介 <Asp.Net Core3 + Vue3入坑教程> 此教程仅适合新手入门或者前后端分离尝试者.可以根据图文一步一步进操作编码也可以选择直接查看源码.每一篇文章都有对应的源码 教程后 ...

  8. SpringBoot初探之Swagger配置

    Swagger是一个用于描述和测试restful接口的工具,只要在定义restful接口时增加一些类和方法的描述注解,通过很简单的配置就可以得到一个展示接口定义页面,也可以在页面上设置参数提交测试接口 ...

  9. swagger配置和简单使用

    说明:本地环境idea + maven3.5 + springboot2.0.0 + springfox-swagger2 2.8.0  + springfox-swagger-ui 2.8.0 +  ...

  10. .net core web api swagger 配置笔记

    参考网址: --配置步骤见如下链接https://docs.microsoft.com/zh-cn/aspnet/core/tutorials/web-api-help-pages-using-swa ...

随机推荐

  1. git的详细使用,项目创建到同步远程仓库,版本回退,忽略文件,分支创建,分支合并,分支名称修改,冲突解决,项目迁移

    注意:此处省略git的安装 1..git的工作流程示意图: 2.本地仓库的初始化: 2.1 创建一个文件夹,如我创建的是:D:\gitdemo\shop 2.2 进入shop目录,鼠标右键,打开git ...

  2. WPF DataGrid 复合表头 (实现表头合并,自定义表头)

    功能说明: 将 DataGrid嵌套在本控件内,使用Label自定义表头,如果需要上下左右滚动 需要在控件外围添加  ScrollViewer 并且设置  ScrollVisibility 为Auto ...

  3. sprintf_s() 、sprintf()和printf()区别和用法

    转载:https://blog.csdn.net/qq_35608277/article/details/80878802 int sprintf_s(char *buffer,size_t size ...

  4. C/C++的二分查找

    假设有一种温度传感器,已经测得它的电压和温度的对应关系,将电压值以ADC转换后的数字量的值表示,形成温度-AD值的对照表,如下. 大致成一条反比关系的曲线. ADC的底层驱动已经写好,对外有一个接口可 ...

  5. 编程体系结构(07):JavaEE之Web开发

    本文源码:GitHub·点这里 || GitEE·点这里 一.基础概念 1.CS与BS架构 CS架构模式 客户端/服务器(Client/Server)模式,既要编写服务器端程序,也要开发客户端程序,软 ...

  6. Magicodes.IE 2.4版本发布

    今天我们发布了2.4版本,这离不开大家对Magicodes.IE的支持,我们也对大家的意见以及需求不断的进行更新迭代,目前我们的发布频率平均在一周一个beta版本,一个月一个正式版本的更新,我们欢迎更 ...

  7. apline无法向gitlab上传git lfs问题

    1 背景 在k8s中基于alpine做底层系统的容器进行git lfs push操作时,发现报错无法上传成功 Fatal error: Server error: http://git.ops.xxx ...

  8. MySQL 日志详解

    一.MySQL 日志分类 MySQL 日志主要包含:错误日志.查询日志.慢查询日志.事务日志.二进制日志. 错误日志: -log-err (记录启动.运行.停止 MySQL 服务时出现的信息) 查询日 ...

  9. Centos 6.9 安装 php5.6

    1.检查当前安装的PHP包 yum list installed | grep php 如果有安装的PHP包,先删除他们, 如: yum remove php.x86_64 php-cli.x86_6 ...

  10. 线上服务的FGC问题排查

    转载:https://blog.csdn.net/g6U8W7p06dCO99fQ3/article/details/106088467 线上服务的GC问题,是Java程序非常典型的一类问题,非常考验 ...