Swagger2使用教程

2020-09-13  本文已影响0人  kacen

我是kacen,一个会点前端的java后端开发工程师。
今天来插曲一下,来介绍一下Swagger的使用。

简介

  Swagger是为了解决企业中接口(api)中定义统一标准规范的文档生成工具。方便各大后端小基友的懒问题,但是写注解也是妥妥的麻烦,但是如果版本迭代快或者人员的流动性大,会导致很多问题。所以很多企业中都会有统一的规范文档,来定义接口标准。

注释和参数讲解

参数说明:
name -- 参数名
value -- 参数说明
required -- 是否必须填写
dataType -- 数据类型
paramType -- 参数类型
example -- 举例
常用注解说明:

表示标识这个类是swagger的资源

表示一个http请求的操作

表示对参数的添加元数据(说明或是否必填等)

表示对类进行说明,用于参数用实体类接收

表示对model属性的说明或者数据操作更改

表示这个方法或者类被忽略

表示单独的请求参数

具体使用说明:

1.@Api()
  ···
  @Api("测试用例1")
  @Controller
  public class swaggerTestUse(){
  }
2.@ApiOperation()
···
@Api("测试用例1")
@Controller
public class swaggerTestUse(){
    @ApiOperation(value = "apiOperationSwaggerTest", notes = "apiOperationSwagger测试")
    public void apiOperationSwaggerTest(){
    }
}
3.@ApiParam()
···
@Api("测试用例1")
@Controller
public class swaggerTestUse(){
    @ApiOperation(value = "apiOperationSwaggerTest", notes = "apiOperationSwagger测试")
    public void apiOperationSwaggerTest(@ApiParam(name = "id", value = "id入参", required = true) Integer id){
    }
}
4.@ApiModel()
···
@ApiModel(description = "测试实体类", value = "测试实体类")
public class Album implements Serializable {
    ···
}

5.@ApiModelProperty()
···
@ApiModel(description = "测试实体类", value = "测试实体类")
public class User implements Serializable {
    @ApiModelProperty(name = "userName", value = "用户名", required = false, exmaple = "小明")
    private String userName;
}

6.@ApiImplicitParams() 和@ApiImplicitParam()这两是兄弟就不分开写了
    ···
  @Api("测试用例1")
  @Controller
  public class swaggerTestUse(){
      @ApiOperation(value = "apiOperationSwaggerTest", notes = "apiOperationSwagger测试")
      @ApiImplicitParams({@ApiImplicitParam(name = "id", value = "id入参", required = true, dataType = "Integer", paramType = "query"),
                        @ApiImplicitParam(name = "brand", value = "brand", required = true, dataType = "BRAND", paramType = "body")
    })
      public void apiOperationSwaggerTest(Integer id, Brand band){
      }
  }

Swagger2实战/Swagger具体使用说明(附带环境参数开关配置和springboot WebConfiguration的实现过滤)

看完以上基本的使用说明,接下来我们就开始实战吧!!!

步骤1:当然是pom文件导入依赖
<!--swagger-->
        <dependency>
            <groupId>io.springfox</groupId>
            <artifactId>springfox-swagger2</artifactId>
            <version>2.9.2</version>
        </dependency>
        <dependency>
            <groupId>io.springfox</groupId>
            <artifactId>springfox-swagger-ui</artifactId>
            <version>2.9.2</version>
        </dependency>
步骤2:启动类添加@EnableSwagger2注解
@SpringBootApplication
@EnableSwagger2
@ComponentScan(basePackages = {""})//为什么写这个,有的小伙伴扫不到包的请手动扫包
public class ServiceGoodsApplication {
    public static void main(String[] args) {
        SpringApplication.run(ServiceGoodsApplication.class);
    }
}
步骤3:编写SwaggerConfig文件
@EnableSwagger2
@Configuration
//Profile是方法1(只在dev和test环境下开启)
@Profile({"dev","test"})
public class SwaggerConfig implements WebMvcConfigurer {
    //是否开启swagger,正式环境一般是需要关闭的,可根据springboot的多环境配置进行设置
    //这个是方法2哦,使用的话在new Docket里添加.Enable方法将参数放入即可
    @Value(value = "${swagger.show}")
    private Boolean swaggerEnabled;

    /**
    * apiInfo() 增加API相关信息
    * 所有的注解
    * .apis(RequestHandlerSelectors.any()) 
    * 指定部分注解1.Api.class(@APi),2.ApiOperation.class(@ApiOperation),3.ApiImplicitParam.class(@ApiImplicitParam)
    *.apis(RequestHandlerSelectors.withMethodAnnotation(Api.class))
    * 指定包路径
    * .apis(RequestHandlerSelectors.basePackage("这里填写需要的路径"))
    * .paths() 这个是包路径下的路径,PathSelectors.any()是包下所有路径
    */
    @Bean
    public Docket createRestApi() {
        log.info(""+swaggerEnabled);
        return new Docket(DocumentationType.SWAGGER_2)
                .useDefaultResponseMessages(false)
                .apiInfo(apiInfo())
                .select()
                .apis(RequestHandlerSelectors.any())
                .paths(PathSelectors.any())
                //创建
                .build();
    }

    private ApiInfo apiInfo() {
        return new ApiInfoBuilder()
                .title("SpringBoot-Swagger2集成")
                .description("springboot | swagger")
                // 作者信息
                .contact(new Contact("kacen", "https://www.baidu.com", "abc@qq.com"))
                .version("0.0.1")
                .build();
    }

    //这个是可要可不要的,具体看需求
    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        registry.addResourceHandler("/js/**").addResourceLocations("classpath:/js/");
        registry.addResourceHandler("swagger-ui.html")
                .addResourceLocations("classpath:/META-INF/resources/");
        registry.addResourceHandler("/webjars/**")
                .addResourceLocations("classpath:/META-INF/resources/webjars/");
    }

}

看到这里有小伙伴在想要指定多包路径,但是又不要整个项目那要怎么办呢,让我带你搞一波,
点击这里看多包配置哦

步骤4:

大功告成啦,请输入http://服务器ip:端口/swagger-ui.html#/看看你的专属文档吧

提示:

 对于是否暴露swagger,我提供的环境开关配置只是其中之一哦,更多的项目采用的是将页面放到静态页面,再用nginx进行转发后,指定代理环境访问哦。想了解的可以自己试一下哦。

上一篇 下一篇

猜你喜欢

热点阅读