前后端分离之swagger

Swagger简介

前后端分离

  • 前端 -> 前端控制层、视图层
  • 后端 -> 后端控制层、服务层、数据访问层
  • 前后端通过API进行交互
  • 前后端相对独立且松耦合
  • 前后端可以部署在不同的服务器上

产生的问题

  • 前后端集成,前端或者后端无法做到“及时协商,尽早解决”,最终导致问题集中爆发

解决方案

  • 首先定义schema [ 计划的提纲 ],并实时跟踪最新的API,降低集成风险

Swagger

  • 号称世界上最流行的API框架
  • Restful Api 文档在线自动生成器 => API 文档 与API 定义同步更新
  • 直接运行,在线测试API
  • 支持多种语言 (如:Java,PHP等)
  • 官网:https://swagger.io/

SpringBoot集成Swagger

  • SpringBoot集成Swagger => springfox,两个jar包

    • Springfox-swagger2
    • swagger-springmvc

    步骤:

    1、新建一个SpringBoot-web项目

    2、添加Maven依赖-----如果刷新不出来http://localhost:8080/swagger-ui.html,可能是依赖的版本不对

    <!-- https://mvnrepository.com/artifact/io.springfox/springfox-swagger2 -->
            <dependency>
                <groupId>io.springfox</groupId>
                <artifactId>springfox-swagger2</artifactId>
                <version>2.8.0</version>
            </dependency>
            <!-- https://mvnrepository.com/artifact/io.springfox/springfox-swagger-ui -->
            <dependency>
                <groupId>io.springfox</groupId>
                <artifactId>springfox-swagger-ui</artifactId>
                <version>2.8.0</version>
            </dependency>
    

    3、编写HelloController,测试确保运行成功!

    package com.itnoob.controller;
    
    import org.springframework.web.bind.annotation.RequestMapping;
    import org.springframework.web.bind.annotation.RestController;
    
    @RestController
    public class HelloController {
        
        
        @RequestMapping(value = "/hello")
        public String hello(){
            return "hello";
        }
    }
    

    4、要使用Swagger,我们需要编写一个配置类-SwaggerConfig来配置 Swagger

    package com.itnoob.config;   
    import org.springframework.context.annotation.Configuration;
    import springfox.documentation.swagger2.annotations.EnableSwagger2;
    
    @Configuration
    @EnableSwagger2//开启Swagger2
    public class SwaggerConfig {
    }
    

    5、访问测试 :http://localhost:8080/swagger-ui.html ,可以看到swagger的界面;

配置Swagger

1、Swagger实例Bean是Docket,所以通过配置Docket实例来配置Swaggger。------可以看源码学习一下

package com.itnoob.config;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import springfox.documentation.service.ApiInfo;
import springfox.documentation.service.Contact;
import springfox.documentation.service.VendorExtension;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2;
import java.util.ArrayList;

/**
 * @author noob
 * @created 2020-09 02 11:31
 */
@Configuration
@EnableSwagger2//开启Swagger2
public class SwaggerConfig {

    //1:配置swagger的Docket的Bean实例
    @Bean
    public Docket docket(){
//3:Docket 实例关联上 apiInfo()
        return new Docket(DocumentationType.SWAGGER_2)
                .apiInfo(apiInfo());
    }


    //2配置Swagger信息=apiInfo
    private ApiInfo apiInfo(){
        //作者信息
        Contact contact = new Contact("小周", "www.itnoob.com", "923737xxx@qq.com");
        return new ApiInfo(
                "小周的Api Documentation",
                "小周Api Documentation",
                "1.1", "urn:tos",
                contact,
                "Apache 2.1",
                "http://www.apache.org/licenses/LICENSE-2.0",
                new ArrayList<VendorExtension>());
    }
}

配置扫描接口

1:构建Docket时通过select()方法配置怎么扫描接口

   @Bean
    public Docket docket(){
//        可以查看源码
        return new Docket(DocumentationType.SWAGGER_2)
                .apiInfo(apiInfo())
               // 通过.select()方法,去配置扫描接口,RequestHandlerSelectors配置如何扫描接口
                .select()
                //RequestHandlerSelectors;配置要扫描的接口的方式
                //basePackage:指定要扫描的包
                //any():扫描全部
                //none():不扫描
                //withClassAnnotation:扫描类上的注解,参数是一个注解的反射对象
                //withMethodAnnotation:扫描方法上的注解
                .apis(RequestHandlerSelectors.basePackage("com.itnoob.controller"))
                //path(): 过滤什么路径
                //该路径下的接口就不会显示在ui界面了
                .paths(PathSelectors.ant("/itnoob/**")) 
                .build();
    }

配置Swagger开关

1、通过enable()方法配置是否启用swagger,如果是false,swagger将不能在浏览器中访问了

//配置swagger的Docket的Bean实例
    @Bean
    public Docket docket(){
//        可以查看源码
        return new Docket(DocumentationType.SWAGGER_2)
                .apiInfo(apiInfo())
                .enable(false)  //关掉swagger
                .select()
                .apis(RequestHandlerSelectors.basePackage("com.itnoob.controller"))
                .paths(PathSelectors.ant("/itnoob/**"))
                .build();
    }

2、如何动态配置当项目处于test、dev环境时显示swagger,处于prod时不显示?

1:application.properties          spring.profiles.active=dev
2:application-dev.properties		server.port=8081
3:application-prod.properties		server.port=8082
  • 判断是不是生产环境
  • 注入enable(flag)
@Bean
    public Docket docket(Environment environment){
        
        //1.1设置要显示的Swagger环境
        Profiles profiles = Profiles.of("dev","test");
        
        //1.2 通过environment.acceptsProfiles  判断是否处在自己设定的环境当中
        boolean flag = environment.acceptsProfiles(profiles);


//        可以查看源码
        return new Docket(DocumentationType.SWAGGER_2)
                .apiInfo(apiInfo())
                .enable(flag)    //1.3 修改标志
                .select()
                .apis(RequestHandlerSelectors.basePackage("com.itnoob.controller")
                .paths(PathSelectors.ant("/itnoob/**"))
                .build();
    }

配置API分组

1、如果没有配置分组,默认是default。通过groupName()方法即可配置分组:

@Bean
public Docket docket(Environment environment) {
   return new Docket(DocumentationType.SWAGGER_2).apiInfo(apiInfo())
      .groupName("hello") // 配置分组
       // 省略配置....
}

2、如何配置多个分组?配置多个分组只需要配置多个docket即可

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

实体配置

1、新建一个实体类

package com.itnoob.pojo;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;

@ApiModel("用户实体类")
public class User {
    @ApiModelProperty("用户名")
    private String username;
    @ApiModelProperty("密码")
    private String password;
    
 //getter and setter...   
}

2、只要这个实体在请求接口的返回值上(即使是泛型),都能映射

@PostMapping("/user")
    public User user(){
        return new User();
    }

@ApiModel为类添加注释

@ApiModelProperty为类属性添加注释

常用注解

Swagger的所有注解定义在io.swagger.annotations包

controller

    @ApiOperation("hello控制类")
    @GetMapping("/hello2")
    public String hello2(@ApiParam("用户名") String username){
        return "hello2"+ username;
    }

皮肤切换

1:bootstrap-ui 访问 http://localhost:8080/doc.html

<dependency>
    <groupId>com.github.xiaoymin</groupId>
    <artifactId>swagger-bootstrap-ui</artifactId>
    <version>1.9.1</version>
</dependency>

参考资料:B站狂神说java https://mp.weixin.qq.com/s/0-c0MAgtyOeKx6qzmdUG0w

原文地址:https://www.cnblogs.com/zhoujun007/p/13602040.html