Swagger 学习--从陌生到初步使用

Swagger

Swagger简介

历史变更

当前主流前后端分离:vue + Springboot

后端时代:前端只用管理静态页面 ;html ==> 后端。模板引擎 jsp ==>后端就是主力

前后端分离时代:

  • 后端 : 后端控制层、服务层、数据访问层 【后端团队】
  • 前端:前端控制层,视图层 【前端团队】
    • 伪造后端数据,json。已经存在了,不需要后端,前端工程依旧能跑
  • 前后端如何交互? ===> API
  • 前后端相对独立,松耦合;
  • 前后端甚至可以部署在不同的服务器上;

产生一个问题:

  • 前后端集成联调,前端人员和后端人员无法做到"即时协商,尽早解决",最终导致问题集中爆发;

解决方案:

  • 首先指定schema [计划的提纲],实时更新最新API,降低集成的风险;
  • 早些年:指定word计划文档;
  • 前后端分离:
    • 前端测试后端接口:postman
    • 后端提供接口,需要实时更新最新的消息及改动!

Swagger的作用

  • 号称世界上最流行的Api框架:

  • RESTFul Api文档在线自动生成工具 => Api文档与API定义同步更新

  • 直接运行,可以在线测试API接口;

  • 支持多种语言: (java,Php)

官网: https://swagger.io/

swagger核心包:

  • swagger2
  • swagger-ui

SpringBoot集成Swagger

1、新建Springboot + web模块的项目

2、导入Swagger相关依赖

<!-- RESTful APIs swagger2 -->
        <dependency>
            <groupId>io.springfox</groupId>
            <artifactId>springfox-swagger2</artifactId>
            <version>${swagger.version}</version>
            <exclusions>
                <exclusion>
                    <groupId>io.swagger</groupId>
                    <artifactId>swagger-annotations</artifactId>
                </exclusion>
                <exclusion>
                    <groupId>io.swagger</groupId>
                    <artifactId>swagger-models</artifactId>
                </exclusion>
            </exclusions>
        </dependency>
        <dependency>
            <groupId>io.springfox</groupId>
            <artifactId>springfox-swagger-ui</artifactId>
            <version>${swagger.version}</version>
        </dependency>
        <dependency>
            <groupId>io.swagger</groupId>
            <artifactId>swagger-annotations</artifactId>
            <version>1.5.21</version>
        </dependency>
        <dependency>
            <groupId>io.swagger</groupId>
            <artifactId>swagger-models</artifactId>
            <version>1.5.21</version>
        </dependency>

3、编写hello控制器

@RESTController
public class HelloController {
    @RequestMapping(value="/hello")
    public String hello(){
        return "hello";
    }
}

4、 配置Swagger信息

因为springboot中没有对Swagger的自动装配,我们需要手动配置Swagger

SwaggerConfig.java

其中的apiInfo有两种写法,一种是直接通过构造函数创建,一种是通过工厂模式创建。

@Configuration
@EnableSwagger2
public class SwaggerConfig {
	@Bean
    public Docket docket(){
        return new Docket(DocumentationType.SWAGGER_2)
                .apiInfo(apiInfo());
    }

    @Bean
    public ApiInfo apiInfo(){
        Contact contact = new Contact("Syz", "https://blog.csdn.net/qq_38648933", "837284303@qq.com");  //作者信息
        return new ApiInfo(
                "微信小程序API开发",//tittle
                "record YZ api",//desc
                "1.0",//versiono
                "https://blog.csdn.net/qq_38648933",//
                contact,//Personal msg
                "Apache 2.0",
                "http://www.apache.org/licenses/LICENSE-2.0",
                new ArrayList<VendorExtension>());

    }
}

1、首先,Swagger的配置信息可以通过实例一个Docket来配置相关信息。如不配置也可运行。

2、查看 Docket 源码,发现Docket只有一个有参的构造函数且需要一个参数 DocumentationType ,进入到DocumentationType,发现有3个DocumentationType,我们用到第二个,所以DocumentationType.SWAGGER_2 即可。

public static final DocumentationType SWAGGER_12 = new DocumentationType("swagger", "1.2");
  public static final DocumentationType SWAGGER_2 = new DocumentationType("swagger", "2.0");
  public static final DocumentationType SPRING_WEB = new DocumentationType("spring-web", "1.0");

3、配置Api文档的其他信息

Docket中有函数apiInfo(),用于设置Docket中的一个成员变量apiInfo,该变量用于描述接口文档。

5、Swagger配置扫描接口

Docket.select()

	@Bean
    public Docket docket(){
        return new Docket(DocumentationType.SWAGGER_2)
                .apiInfo(apiInfo())
            	// .enable 是否启动 Swagger
                .select()
                //apis设置扫描接口
                // RequestHandlerSelectors
                // .basePackage() 基于包扫描
                // .any() 全部
                // .none() 都不
                // .withClassAnnotation() 基于类上的某个注解
                // .withMethodAnnotation() 基于方法上的某个注解
                .apis(RequestHandlerSelectors.basePackage("com.syz.controller"))
                // paths过滤接口路径,只有包含antPattern的请求路径才会被扫描
                .paths(PathSelectors.ant("/syz/**"))
                .build();//build 工厂模式
    }
		public ApiInfo apiInfo(){
        Contact contact = new Contact("Syz", "https://blog.csdn.net/qq_38648933", "837284303@qq.com");  //作者信息
        return new ApiInfoBuilder()
                .title("微信小程序api接口文档")
                .contact(contact)
                .build();
//      上面的是用工厂模式创建,下面是直接用构造器构造,底层是一样的
//      return new ApiInfo(
//                "微信小程序API开发",
//                "record YZ api",
//                "1.0",
//                "https://blog.csdn.net/qq_38648933",
//                new Contact("", "", ""),
//                "Apache 2.0",
//                "http://www.apache.org/licenses/LICENSE-2.0",
//                new ArrayList<VendorExtension>());

    }

6、通过获取项目的环境开启Swagger

在application-dev.yal中配置

#是否开启 swagger-ui
swagger:
  enabled: true

然后获取该信息

	@Value("${swagger.enabled}")
    private Boolean enabled;
	@Bean
    public Docket docket(){
        return new Docket(DocumentationType.SWAGGER_2)
                .apiInfo(apiInfo())
                .enable(enabled)
                .select()
                .apis(RequestHandlerSelectors.basePackage("com.syz.controller"))
                .build();//build 工厂模式
    }

这样可以通过不同的配置环境来控制Swagger-ui的开关。

7、配置API文档的分组(协同开发)

.groupName("耀祖")

如何配置多个分组:创建多个Docket实例

8、常用注解

1)@Api(value=“说明类的作用”,tags=“说明类的作用,非空时覆盖value”)

2)@ApiOperation(value=“说明方法的用途、作用”,notes=“方法的备用说明”)

3)@ApiParam(value=“参数说明”,defaultValue=“默认值”,required=“是否必填,默认false”)

4)@ApiImplicitParams

​ 用在请求的方法上,表示一组参数说明,@ApiImplicitParam:用在@ApiImplicitParams注解中,指定一个请求参数的方方面面

@ApiImplicitParams({
      @ApiImplicitParam(name = "name", value = "用户名", 
                        required = false, paramType = "query", dataType = "String"),
      @ApiImplicitParam(name = "pass", value = "密码", 
                        required = false, paramType = "query", dataType = "String") 
})
public UserModel login(@RequestParam(value = "name", required = false) String account,
                @RequestParam(value = "pass", required = false) String password){}

paramType:参数放在哪个地方
· header --> 请求参数的获取:@RequestHeader
· query --> 请求参数的获取:@RequestParam
· path(用于restful接口)–> 请求参数的获取:@PathVariable

5)@ApiModel(value=“该类的信息”,description=“描述”)

​ 用于描述实体类

总结:

  1. 我们可以通过Swagger给一些比较难理解的属性或者接口,增加注释信息
  2. 接口文档实时更新
  3. 可以在线调试

Swagger是一个优秀的工具,几乎所有大公司都有使用它。

【注意点】在正式发布的时候,关闭Swagger!!!出于安全考虑,同时节省内存。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值