• SpringBoot集成Swagger(Swagger的使用),生成接口文档,方便前后端分离开发


    首先上一张成果图。

     1、Maven依赖

            <dependency>
                <groupId>io.springfox</groupId>
                <artifactId>springfox-swagger2</artifactId>
                <version>2.7.0</version>
            </dependency>
            <!-- swagger-ui 用于查看的 -->
            <dependency>
                <groupId>io.springfox</groupId>
                <artifactId>springfox-swagger-ui</artifactId>
                <version>2.7.0</version>
            </dependency>

    2、需要自定义一个配置类,然后添加到Spring容器中。

    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.spi.DocumentationType;
    import springfox.documentation.spring.web.plugins.Docket;
    import springfox.documentation.swagger2.annotations.EnableSwagger2;
    
    //
    @Configuration   //声明此类是配置类
    @EnableSwagger2 // 支持Swagger
    public class Swagger2Configuration {
        @Bean
        public Docket createRestApi() {
            return new Docket(DocumentationType.SWAGGER_2)
                    .apiInfo(apiInfo())
                    .select()
                    .apis(RequestHandlerSelectors.basePackage("com.xuecheng"))//扫描的路劲,代表com.xuecheng下面的类都可以被扫到
                    .paths(PathSelectors.any())
                    .build();
        }
    
        private ApiInfo apiInfo() {
            return new ApiInfoBuilder()
                    .title("Swaggerapi文档")
                    .description("Swaggerapi文档")
    //                .termsOfServiceUrl("/")
                    .version("1.0")
                    .build();
        }
    }

    3、常用注解介绍

    @Api 修饰整个类,描述Controller的作用,

    @ApiOperation 描述一个类的方法,或者说一个接口

    @ApiParam 单个参数描述

    @ApiModel 用对象来接收参数

    @ApiModelProperty 属性注释,用于对象属性上

    @ApiResponse HTTP响应整体描述

    @ApiError 发生错误的返回信息

    @ApimplicitParam 一个请求参数

    @ApimplicitParams 多个请求参数

    4、接口书写

     因为参数中还有一个对象,所以再对象的属性上也可以加注解,描述。

    5、启动项目,访问localhost:xx/wagger-ui.html,即可访问接口文档。文章开头有图。

    6、Swagger接口生成工作原理。

    (1)、系统启动,扫描到api工程中的Swagger2Configuration类

    (2)、在此类中指定了包路径com.xuecheng,找到在此包下及子包下标记有@RestController注解的controller类

    (3)、根据controller类中的Swagger注解生成接口文档。

    7、接口测试

      打开接口文档页面,输入请求参数,点击“Try it out”发起请求。即可向项目发请求,用于测试。

      

  • 相关阅读:
    设计模式系列之-抽象工厂
    设计模式系列之-工厂方法
    设计模式系列之-简单工厂
    键盘事件keydown、keypress、keyup随笔整理总结(摘抄)
    js 方法重载
    JS禁止右键
    jquery.validate运用和扩展
    Javascript Math.ceil()与Math.round()与Math.floor()区别
    Jquery操作下拉框(DropDownList)实现取值赋值
    jquery中attr和prop的区别
  • 原文地址:https://www.cnblogs.com/super-hu/p/12033445.html
Copyright © 2020-2023  润新知