接口规范swagger

1. 为什么需要

  • 接口测试人员要通过接口描述测试接口 --黑盒测试
  • 前端开发人员要通过接口描述使用接口.

2. 写接口doc文档

  • 直接整理出所有接口,每个接口有访问地址(访问方式),参数及返回值.
  • 可以直接通过后端代码产生能够让前台开发或测试人员能够看懂生成的swagger文档

3. 实现

  • 引入swagger需要的jar包
<!-- swagger引入包-->
	<properties>
        <!--swagger对应的版本-->
        <springfox.version>2.4.0</springfox.version>
    </properties>
        <dependency>
            <groupId>io.springfox</groupId>
            <artifactId>springfox-swagger2</artifactId>
            <version>${springfox.version}</version>
        </dependency>
        <dependency>
            <groupId>io.springfox</groupId>
            <artifactId>springfox-swagger-ui</artifactId>
            <version>${springfox.version}</version>
        </dependency>
  • 编写SwaggerConfig 类
package cn.wxy.crm.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
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;

//springboot  Configuration 相当于写一个applicationContext.xml
@Configuration
@EnableWebMvc  //开关配置 开启webmvc
@EnableSwagger2 //开启swagger配置
@ComponentScan(basePackages= "cn.wxy.crm.web.controller") //扫描controller
public class SwaggerConfig {

    //相当于 <bean id="api" class=""Docket/>
    @Bean
    public Docket api(){
        return new Docket(DocumentationType.SWAGGER_2)
                .apiInfo(this.apiInfo())
                .select()
                .apis(RequestHandlerSelectors.basePackage("cn.wxy.crm.web.controller"))
                .paths(PathSelectors.any())
                .build();
    }
    
    //生成内容 接口的信息
    private ApiInfo apiInfo(){
         @SuppressWarnings("deprecation")
         ApiInfo info=new ApiInfo(
                 "crm的接口文档",
                 "王哈哈",
                 "1.0",
                 "www.wxy.cn",
                 "王哈哈",
                 "1",
                 "www.wxy.cn");
         return info;
    }
}
  • 在applicationContext-mvc.xml文件中扫描swagger包
<!-- 把swagger交给spring-->
    <context:component-scan base-package="cn.wxy.crm.config"></context:component-scan>

4. 运行

http://localhost/swagger-ui.html

5. 效果展示

在这里插入图片描述

发布了33 篇原创文章 · 获赞 0 · 访问量 417

猜你喜欢

转载自blog.csdn.net/weixin_45737653/article/details/104502179