使用Swagger实现接口版本号管理方式

 更新时间:2021年10月13日 12:01:37   作者:被迫成为奋斗b  
这篇文章主要介绍了使用Swagger实现接口版本号管理方式,具有很好的参考价值,希望对大家有所帮助。如有错误或未考虑完全的地方,望不吝赐教

Swagger实现接口版本号管理

前言:使用swagger暴露对外接口时原则是每个系统在不同的迭代版本仅仅需要暴露该迭代版本的接口给外部使用,客户端不需要关心不相关的接口

先来看张效果图

下面是实现代码:

定义注解ApiVersion:

/**
 * 接口版本管理注解
 * @author 周宁
 * @Date 2018-08-30 11:48
 */
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
public @interface ApiVersion {
 
    /**
     * 接口版本号(对应swagger中的group)
     * @return String[]
     */
    String[] group();
 
}

定义一个用于版本常量的类ApiVersionConstant

/**
 * api版本号常量类
 * @author 周宁
 * @Date 2018-08-30 13:30
 */
public interface ApiVersionConstant {
    /**
     * 图审系统手机app1.0.0版本
     */
    String FAP_APP100 = "app1.0.0";
 
}

更改SwaggerConfig添加Docket(可以理解成一组swagger 接口的集合),并定义groupName,根据ApiVersion的group方法区分不同组(迭代)的接口,代码如下:

@Configuration
@EnableSwagger2
@EnableWebMvc
public class SwaggerConfig {
    
    //默认版本的接口api-docs分组
    @Bean
    public Docket vDefault(){
        return new Docket(DocumentationType.SWAGGER_2)
                .apiInfo(buildApiInf())
                .select()
                .apis(RequestHandlerSelectors.basePackage("com.gysoft"))//controller路径
                .paths(PathSelectors.any())
                .build();
    }
    //app1.0.0版本对外接口
    @Bean
    public Docket vApp100(){
        return new Docket(DocumentationType.SWAGGER_2)
                .apiInfo(buildApiInf())
                .groupName(FAP_APP100)
                .select()
                .apis(input -> {
                    ApiVersion apiVersion = input.getHandlerMethod().getMethodAnnotation(ApiVersion.class);
                    if(apiVersion!=null&&Arrays.asList(apiVersion.group()).contains(FAP_APP100)){
                        return true;
                    }
                    return false;
                })//controller路径
                .paths(PathSelectors.any())
                .build();
    }
 
    private ApiInfo buildApiInf(){
        return new ApiInfoBuilder()
                .title("接口列表")
                .termsOfServiceUrl("http://127.0.0.1:8080/swagger-ui.html")
                .description("springmvc swagger 接口测试")
                .version("1.0.0")
                .build();
    } 
}

立即食用

/**
 * @author 周宁
 * @Date 2018-08-24 11:05
 */
@RestController
@RequestMapping("/document")
@Api(value = "资料文档或者CAD图纸", description = "资料文档或者CAD图纸")
public class DocumentController extends GyBasicSession {
 
    private static final Logger logger = LoggerFactory.getLogger(DocumentController.class);
 
    @ApiImplicitParams({@ApiImplicitParam(name = "page", value = "当前页数", dataType = "int", paramType = "path"),
            @ApiImplicitParam(name = "pageSize", value = "每页大小", dataType = "int", paramType = "path"),
            @ApiImplicitParam(name = "projectId", value = "项目id", dataType = "string", paramType = "path"),
            @ApiImplicitParam(name = "stageNum", value = "阶段编号", dataType = "string", paramType = "path"),
            @ApiImplicitParam(name = "type", value = "0资料(文档);1cad图纸", dataType = "int", paramType = "path"),
            @ApiImplicitParam(name = "searchkey", value = "搜索关键字", dataType = "string", paramType = "query")})
    @ApiOperation("分页获取资料文档(CAD图纸)列表数据")
    @GetMapping("/pageQueryAppDocumentInfo/{page}/{pageSize}/{projectId}/{stageNum}/{type}")
    @ApiVersion(group = ApiVersionConstant.FAP_APP100)
    public PageResult<AppDocumentInfo> pageQueryAppDocumentInfo(@PathVariable Integer page, @PathVariable Integer pageSize, @PathVariable String projectId, @PathVariable String stageNum, @PathVariable Integer type, @RequestParam String searchkey) {
        return null;
    } 
}

使用swagger测试接口

swagger:自动扫描 controller 包下的请求,生成接口文档,并提供测试功能。

引入依赖

       <!-- 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>

在 config 包引入 swagger 自定义配置类

package com.zhiyou100.zymusic.config;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import springfox.documentation.builders.ApiInfoBuilder;
import springfox.documentation.builders.PathSelectors;
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 teacher
 * @date 2019/9/25
 */
@Configuration
@EnableSwagger2
public class MySwaggerConfiguration {
    @Bean
    public Docket createRestApi() {
        return new Docket(DocumentationType.SWAGGER_2)
                .apiInfo(apiInfo())
                .select()
                .apis(RequestHandlerSelectors.any())
                .paths(PathSelectors.any())
                .build();
    }
    private ApiInfo apiInfo() {
        return new ApiInfoBuilder()
                //标题
                .title("Spring Boot 中使用 Swagger2 构建 RESTful APIs")
                //简介
                .description("hello swagger")
                //服务条款
                .termsOfServiceUrl("1. xxx\n2. xxx\n3. xxx")
                //作者个人信息
                .contact(new Contact("admin", "http://www.zhiyou100.com", "admin@zhiyou100.com"))
                //版本
                .version("1.0")
                .build();
    }
}

启动项目后,使用 http://localhost:8080/swagger-ui.html

选择需要测试的接口:Try it out -> 填写参数 -> Execute -> 查看响应

以上为个人经验,希望能给大家一个参考,也希望大家多多支持脚本之家。

相关文章

  • mybatis学习笔记之mybatis注解配置详解

    mybatis学习笔记之mybatis注解配置详解

    本篇文章主要介绍了mybatis学习笔记之mybatis注解配置详解,小编觉得挺不错的,现在分享给大家,也给大家做个参考。一起跟随小编过来看看吧
    2017-12-12
  • 详解Java实现简单SPI流程

    详解Java实现简单SPI流程

    这篇文章主要介绍了Java实现简单SPI流程,SPI英文全称为Service Provider Interface,顾名思义,服务提供者接口,它是jdk提供给“服务提供厂商”或者“插件开发者”使用的接口
    2023-03-03
  • Java 爬虫如何爬取需要登录的网站

    Java 爬虫如何爬取需要登录的网站

    这篇文章主要介绍了Java 爬虫如何爬取需要登录的网站,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下
    2019-10-10
  • springboot泛型封装开发方式

    springboot泛型封装开发方式

    这篇文章主要介绍了springboot泛型封装开发方式,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教
    2023-12-12
  • 玩转spring boot 结合jQuery和AngularJs(3)

    玩转spring boot 结合jQuery和AngularJs(3)

    玩转spring boot,这篇文章主要介绍了结合jQuery和AngularJs,玩转spring boot,具有一定的参考价值,感兴趣的小伙伴们可以参考一下
    2017-01-01
  • Java简明解读代码块的应用

    Java简明解读代码块的应用

    所谓代码块是指用"{}"括起来的一段代码,根据其位置和声明的不同,可以分为普通代码块、构造块、静态块、和同步代码块。如果在代码块前加上 synchronized关键字,则此代码块就成为同步代码块
    2022-07-07
  • 重新理解Java泛型

    重新理解Java泛型

    这篇文章主要介绍了重新理解Java泛型,具有一定参考价值,需要的朋友可以了解下。
    2017-11-11
  • springboot配置开发和测试环境并添加启动路径方式

    springboot配置开发和测试环境并添加启动路径方式

    这篇文章主要介绍了springboot配置开发和测试环境并添加启动路径方式,具有很好的参考价值,希望对大家有所帮助。如有错误或未考虑完全的地方,望不吝赐教
    2021-11-11
  • JAVA面试题 从源码角度分析StringBuffer和StringBuilder的区别

    JAVA面试题 从源码角度分析StringBuffer和StringBuilder的区别

    这篇文章主要介绍了JAVA面试题 从源码角度分析StringBuffer和StringBuilder的区别,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,下面我们来一起学习下吧
    2019-07-07
  • Java中Stream API的使用示例详解

    Java中Stream API的使用示例详解

    Java 在 Java 8 中提供了一个新的附加包,称为 java.util.stream,该包由类、接口和枚举组成,允许对元素进行函数式操作, 本文主要介绍了Java中Stream API的具体使用,感兴趣的小伙伴可以了解下
    2023-11-11

最新评论