Swagger介绍与使用

Table of Contents

前后端分离

Swagger简介

SpringBoot 集成 Swagger

配置Swagger信息

Swagger配置扫描接口

分组

实体类配置

注释

总结


前后端分离

Vue + SpringBoot

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

前后端分离时代:

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

产生一个问题:

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

解决方案

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

Swagger简介

  • 号称世界上最流行的API框架;
  • RestFul Api 文档在线自动生成工具 => Api文档与API定义同步更新;
  • 直接运行,可以在线测试API接口;
  • 支持多种语言:(Java、PHP......)

官网:https://swagger.io/

在项目中使用Swagger需要 springbox(包);

  • swagger2
  • ui

SpringBoot 集成 Swagger

1、新建一个SpringBoot(Web项目)

2、引入相关依赖

    	<!-- 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>

3、编写一个Hello工程

4、配置Swagger ==>Config

@Configuration
@EnableSwagger2   //开启Swagger2
public class SwaggerConfig {
}

 5、测试运行http://127.0.0.1:8080/swagger-ui.html

配置Swagger信息

package com.kuang.swagger.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import springfox.documentation.builders.ApiInfoBuilder;
import springfox.documentation.service.ApiInfo;
import springfox.documentation.service.Contact;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2;

@Configuration
@EnableSwagger2   //开启Swagger2
public class SwaggerConfig {

    @Bean
    public Docket createRestApi(){
        return new Docket(DocumentationType.SWAGGER_2)
                .apiInfo(apiInfo());
    }

    //配置Swagger 信息=apiInfo
    private ApiInfo apiInfo() {

        //作者信息
        Contact contact = new Contact("Sen", "https://blog.csdn.net/gjs935219", "[email protected]");
        return new ApiInfoBuilder()
                .title("森的SwaggerAPI文档")
                .description("Swagger的API配置")
                .termsOfServiceUrl("https://blog.csdn.net/gjs935219")
                .contact(contact)
                .version("v1.0")
                .build();
    }
}

Swagger配置扫描接口

    @Bean
    public Docket createRestApi(){
        return new Docket(DocumentationType.SWAGGER_2)
                .apiInfo(apiInfo())
                .select()
                //RequestHandlerSelectors, 配置要扫描接口的方式
                //basePackage()扫描全部
                //any()扫描全部
                //none()不扫描
                //withClassAnnotation()扫描方法上的注解
                .apis(RequestHandlerSelectors.basePackage("com.kuang"))
                //path() 过滤什么路径
                .paths(PathSelectors.any())
                .build();
    }

公司只希望Swagger在生产环境中使用,在发布的时候不使用???

通过开发、上线的生产环境来判断

一个开发环境,一个开发完成后发布的环境

 

通过下面代码,环境的配置,来选择使用哪一个环境。 

package com.kuang.swagger.config;

import org.springframework.context.EnvironmentAware;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.env.Environment;
import org.springframework.core.env.Profiles;
import springfox.documentation.builders.ApiInfoBuilder;
import springfox.documentation.builders.PathSelectors;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.service.ApiInfo;
import springfox.documentation.service.Contact;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2;

@Configuration
@EnableSwagger2   //开启Swagger2
public class SwaggerConfig {

    //配置了Swagger的Docket的bean实例
    @Bean
    public Docket docket(Environment environment){

        //设置要显示的Swagger环境
        Profiles profiles = Profiles.of("dev", "test");

        //通过environment.acceptsProfiles判断是否处于自己设定的环境当中
        boolean flag = environment.acceptsProfiles(profiles);

        return new Docket(DocumentationType.SWAGGER_2)
                .apiInfo(apiInfo())
                .enable(flag)//enable是否启动swagger,如果为false,则Swagger不能在浏览器中访问
                .select()
                //RequestHandlerSelectors, 配置要扫描接口的方式
                //basePackage()扫描全部
                //any()扫描全部
                //none()不扫描
                //withClassAnnotation()扫描方法上的注解
                .apis(RequestHandlerSelectors.basePackage("com.kuang"))
                //path() 过滤什么路径
                .paths(PathSelectors.any())
                .build();
    }

    //配置Swagger 信息=apiInfo
    private ApiInfo apiInfo() {

        //作者信息
        Contact contact = new Contact("Sen", "https://blog.csdn.net/gjs935219", "[email protected]");
        return new ApiInfoBuilder()
                .title("森的SwaggerAPI文档")
                .description("Swagger的API配置")
                .termsOfServiceUrl("https://blog.csdn.net/gjs935219")
                .contact(contact)
                .version("v1.0")
                .build();
    }
}

测试

开发完成之后,只需要运维注释掉即可(发布之后就不能用swagger了)

#spring.profiles.active=dev

分组

.groupName("久森")

如何配置多个分组

答:多个Docket实例即可

部分代码:

@Configuration
@EnableSwagger2   //开启Swagger2
public class SwaggerConfig {

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

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

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

    //配置了Swagger的Docket的bean实例
    @Bean
    public Docket docket(Environment environment){

        //设置要显示的Swagger环境
        Profiles profiles = Profiles.of("dev", "test");

        //通过environment.acceptsProfiles判断是否处于自己设定的环境当中
        boolean flag = environment.acceptsProfiles(profiles);

        return new Docket(DocumentationType.SWAGGER_2)
                .apiInfo(apiInfo())
                .groupName("久森")
                .enable(flag)//enable是否启动swagger,如果为false,则Swagger不能在浏览器中访问
                .select()
                //RequestHandlerSelectors, 配置要扫描接口的方式
                //basePackage()扫描全部
                //any()扫描全部
                //none()不扫描
                //withClassAnnotation()扫描方法上的注解
                .apis(RequestHandlerSelectors.basePackage("com.kuang"))
                //path() 过滤什么路径
                .paths(PathSelectors.any())
                .build();
    }

    //配置Swagger 信息=apiInfo
    private ApiInfo apiInfo() {

        //作者信息
        Contact contact = new Contact("Sen", "https://blog.csdn.net/gjs935219", "[email protected]");
        return new ApiInfoBuilder()
                .title("森的SwaggerAPI文档")
                .description("Swagger的API配置")
                .termsOfServiceUrl("https://blog.csdn.net/gjs935219")
                .contact(contact)
                .version("v1.0")
                .build();
    }
}

实体类配置

实体类:

package com.kuang.swagger.pojo;

public class User {
    public String userName;
    public String password;
}

接口

package com.kuang.swagger.controller;

import com.kuang.swagger.pojo.User;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class HelloController {

    @GetMapping(value = "/hello")
    public String hello(){
        return "hello";
    }

    //只要我们的接口中,返回值中存在实体类,他就会被扫描到swagger中
    @PostMapping(value = "/user")
    public User user(){
        return new User();
    }
}

注释

作用范围                         API                                          使用位置

对象属性                        @ApiModelProperty                用在参数对象的字段上

协议集描述                    @Api                                        用在Conntroller类上

协议描述                        @ApiOperation                        用在controller方法上

Response集                   @ApiResponses                      用在controller方法上

Response                      @ApiResponse                        用在@ApiResponses里面

非对象参数集                 @ApilmplicitParams                用在controller方法上

@ApiModel("用户实体类")
public class User {

    @ApiModelProperty("用户名")
    public String userName;
    @ApiModelProperty("密码")
    public String password;
}

总结

1、我们可以通过Swagger给一些比较难理解的属性或者接口,增加注释信息

2、接口文档实时更新

3、可以在线测试

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

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

猜你喜欢

转载自blog.csdn.net/gjs935219/article/details/109027127