swagger学习笔记

swagger简介

  • 号称世界上最流行的Api框架
  • RestFul Api文档在线生成工具=》Api文档与Api定义同步更新
  • 直接运行,可以在线测试借口
  • 支持多种语言(java,php…)
  • 官网:https://swagger.io/tools/swagger-ui/

在项目中使用Swagger2需要springbox

  • swagger2
  • UI

Springboot集成Swagger

  • 新建一个springboot web项目
  • 导入两个jar包
<!-- 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>

  • 编写Swaggerconfig
package cn.smallcosmos.config;

import org.springframework.context.annotation.Configuration;
import springfox.documentation.swagger2.annotations.EnableSwagger2;

/**
* @Date 2020/5/7 下午6:12
* @Created by zhaoli
*/
@Configuration
@EnableSwagger2 // 开启swagger2
public class SwaggerConfig {

}
  • 启动项目测试一下(http://localhost:8080/swagger-ui.html)
  • 在这里插入图片描述

swagger配置

	//配置swagger2 Docket bean实例
  @Bean
  public Docket docket(){
      return new Docket(DocumentationType.SWAGGER_2)
              .apiInfo(apiInfo());
  }
  //配置swagger信息==>ApiInfo
  private ApiInfo apiInfo(){
      //作者信息
      Contact contact = new Contact("赵力", "http://smallcosmos.cn", "1191599851@qq.com");
      return new ApiInfo("Smallcosmos"
              , "API接口文档"
              , "v1.0"
              , "http://smallcosmos.cn"
              , contact
              , "Apache 2.0"
              , "http://www.apache.org/licenses/LICENSE-2.0"
              , new ArrayList());

  }
  • 配置后效果
  • 在这里插入图片描述

swagger配置扫描借口

				.select()
                //RequestHandlerSelectors 配置要扫描接口方式
                //basePackage指定扫描包
                //any()扫描所有类
                //none()什么都不扫描
                //withClassAnnotation基于类注解扫描
                //withMethodAnnotation基于方法注解扫描
                .apis(RequestHandlerSelectors.basePackage("cn.smallcosmos.controller"))
                //过滤路径
                .paths(PathSelectors.any())
                .build();

配置分组

.groupName("smallcosmos")

配置多个分组(实现多人协同开发)

@Bean
    public Docket docket1(){
        return new Docket(DocumentationType.SWAGGER_2).groupName("A");
    }
    @Bean
    public Docket docket2(){
        return new Docket(DocumentationType.SWAGGER_2).groupName("A");
    }
    @Bean
    public Docket docket3(){
        return new Docket(DocumentationType.SWAGGER_2).groupName("A");
    }

在这里插入图片描述

swagger常用注解

详见这个博客

总结

  • 我们可以通过swagger给一些比较难理解的属性或者接口添加注释信息
  • 接口文档实时更新
  • 可以在线测试
  • 【注意点】在正式发布的时候,关闭swagger!!!出于安全考虑,防止他人调用接口,也可以节省内存。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值