Swagger学习

简介: Swagger学习

Swagger简介


Swagger 是一款RESTFUL接口的文档在线自动生成+功能测试功能软件。

官网:https://swagger.io/

前后端分离会产生一个问题:全后端集成联调,前端人员和后端人员无法做到“即使协商,尽早解决”,最终导致问题集中爆发


解决方案:


  1. 前后端测试接口:postman
  2. 后端提供接口,需要实时更新最新的消息及改动。


Swagger


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


Spring Boot集成Swagger


1,新建一个SpringBoot项目


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工程


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


4,配置Swagger


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


5,测试运行:http://localhost:8080/swagger-ui.html 显示如下页面


7d51347fa4c44bf38b43446b823b5c73.png


配置Swagger


Swagger的bean实例Docker


@Configuration
@EnableSwagger2//开启Swagger2
public class SwaggerConfig {
    public static final Contact DEFAULT_CONTACT = new Contact(
            "qijian",
            "https://blog.csdn.net/qq_43663493?spm=1000.2115.3001.5343",
            "183@qq.com");
    //配置Swagger的Docket的Bean实例
    @Bean
    public Docket docket(){
        return new Docket(DocumentationType.SWAGGER_2)
                .apiInfo(apiInfo());
    }
    private ApiInfo apiInfo(){
        return new ApiInfo(
                "Api Documentation  of qijian",
                "作者最帅",
                "1.0",
                "urn:https://blog.csdn.net/qq_43663493?spm=1000.2115.3001.5343",
                DEFAULT_CONTACT,
                "Apache 2.0",
                "http://www.apache.org/licenses/LICENSE-2.0",
                new ArrayList<VendorExtension>()
        );
    }
}


ec5b441221714f9b92b0c4386f08852b.png


Swagger配置扫描接口


@Configuration
@EnableSwagger2//开启Swagger2
public class SwaggerConfig {
    public static final Contact DEFAULT_CONTACT = new Contact(
            "qijian",
            "https://blog.csdn.net/qq_43663493?spm=1000.2115.3001.5343",
            "183@qq.com");
    //配置Swagger的Docket的Bean实例
    @Bean
    public Docket docket(){
        return new Docket(DocumentationType.SWAGGER_2)
                .apiInfo(apiInfo())
              .enable(true)//是否起用swagger , 当为false时swagger是不能使用的
                .select()
                //RequestHandlerSelectors 配置要扫描接口的方式
                //basePackge:指定扫描的包
                //any():扫描全部
                //none() : 不扫描
                //withClassAnnotation:扫描类上的注解,参数是一个注解的反射对象
                //withMethodAnnotion:扫描方法上的注解
                .apis(RequestHandlerSelectors.basePackage("com.qijian.swagger.controller"))
                //paths() 过滤路径
//                .paths(PathSelectors.ant("com1.qijian.demo"))
                .build();
    }
    private ApiInfo apiInfo(){
        return new ApiInfo(
                "Api Documentation  of qijian",
                "作者最帅",
                "1.0",
                "urn:https://blog.csdn.net/qq_43663493?spm=1000.2115.3001.5343",
                DEFAULT_CONTACT,
                "Apache 2.0",
                "http://www.apache.org/licenses/LICENSE-2.0",
                new ArrayList<VendorExtension>()
        );
    }
}

e267c346bb354793b9e03ded1e634f49.png


当只希望在生产环境中使用,在发布的时候不使用swagger,怎么做?

1,判断是不是生产环境 flag = false

2,注入enable(flag)


    //配置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)//是否起用swagger , 默认为true , 当为false时swagger是不能使用的
                .select()
                //RequestHandlerSelectors 配置要扫描接口的方式
                //basePackge:指定扫描的包
                //any():扫描全部
                //none() : 不扫描
                //withClassAnnotation:扫描类上的注解,参数是一个注解的反射对象
                //withMethodAnnotion:扫描方法上的注解
                .apis(RequestHandlerSelectors.basePackage("com.qijian.swagger.controller"))
                //paths() 过滤路径
//                .paths(PathSelectors.ant("com1.qijian.demo"))
                .build();
    }


配置API的分组


.groupName("A");
• 1


如何配置多个分组,实现多个Docket实例即可


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


项目代码:


目录结构


b77d87fa1e654bb6b9ab3cb3abe3fc23.png


pom.xml


<!-- 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 (swagger配置类)


package com.qijian.swagger.config;
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.PathSelectors;
import springfox.documentation.builders.RequestHandlerSelectors;
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 qijian
 * @version 1.0
 * @description
 * @updateRemark
 * @updateUser
 * @createDate 2021/11/4 20:52
 * @updateDate 2021/11/4 20:52
 **/
@Configuration
@EnableSwagger2//开启Swagger2
public class SwaggerConfig {
    public static final Contact DEFAULT_CONTACT = new Contact(
            "qijian",
            "https://blog.csdn.net/qq_43663493?spm=1000.2115.3001.5343",
            "183@qq.com");
    @Bean
    public Docket docket1(){
        return new Docket(DocumentationType.SWAGGER_2).apiInfo(apiInfo()).groupName("A");
    }
    @Bean
    public Docket docket2(){
        return new Docket(DocumentationType.SWAGGER_2).apiInfo(apiInfo()).groupName("C");
    }
    //配置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)//是否起用swagger , 默认为true , 当为false时swagger是不能使用的
                .select()
                //RequestHandlerSelectors 配置要扫描接口的方式
                //basePackge:指定扫描的包
                //any():扫描全部
                //none() : 不扫描
                //withClassAnnotation:扫描类上的注解,参数是一个注解的反射对象
                //withMethodAnnotion:扫描方法上的注解
                .apis(RequestHandlerSelectors.basePackage("com.qijian.swagger.controller"))
                //paths() 过滤路径
//                .paths(PathSelectors.ant("com1.qijian.demo"))
                .build();
    }
    private ApiInfo apiInfo(){
        return new ApiInfo(
                "Api Documentation  of qijian",
                "作者最帅",
                "1.0",
                "urn:https://blog.csdn.net/qq_43663493?spm=1000.2115.3001.5343",
                DEFAULT_CONTACT,
                "Apache 2.0",
                "http://www.apache.org/licenses/LICENSE-2.0",
                new ArrayList<VendorExtension>()
        );
    }
}


the code of hellocontroller.java


package com.qijian.swagger.controller;
import com.qijian.swagger.pojo.User;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
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;
/**
 * @author qijian
 * @version 1.0
 * @description
 * @updateRemark
 * @updateUser
 * @createDate 2021/11/4 20:47
 * @updateDate 2021/11/4 20:47
 **/
@RestController
public class HelloController {
    @RequestMapping(value = "/hello")
    public String hello(){
        return "hello";
    }
    //只要我的接口中存在实体类,返回值中存在实体类,它就会扫描到Swagger中
    @PostMapping(value = "/user")
    public User user(){
        return new User();
    }
    @ApiOperation("Hello控制2")
    @GetMapping(value = "/hello2")
    public String hello(@ApiParam("用户名") String userName){
        return "hello" + userName;
    }
}


the code of user.java


package com.qijian.swagger.pojo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
/**
 * @author qijian
 * @version 1.0
 * @description
 * @updateRemark
 * @updateUser
 * @createDate 2021/11/4 22:56
 * @updateDate 2021/11/4 22:56
 **/
@ApiModel("用户实体类")
public class User {
    @ApiModelProperty("用户名")
    public String username;
    @ApiModelProperty("密码")
    public String password;
}


启动类:


package com.qijian.swagger;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class SwaggerDemoApplication {
    public static void main(String[] args) {
        SpringApplication.run(SwaggerDemoApplication.class, args);
    }
}


application配置文件

c394344398464507998755cca88faee8.png


总结


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

2,接口文档实时更新

3,可以在线测试


常用注解:


@Api()用于类; 表示标识这个类是swagger的资源 @Api(value="用户controller",tags={"用户操作接口"})

@ApiOperation()用于方法;表示一个http请求的操作

@ApiParam()用于方法,参数,字段说明; 表示对参数的添加元数据(说明或是否必填等)

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

@ApiModelProperty()用于方法,字段 ; 表示对model属性的说明或者数据操作更改

@ApiIgnore()用于类,方法,方法参数 ; 表示这个方法或者类被忽略

@ApiImplicitParam() 用于方法 ; 表示单独的请求参数

@ApiImplicitParams() 用于方法,包含多个 @ApiImplicitParam



文档实时更新


3,可以在线测试


常用注解:


@Api()用于类; 表示标识这个类是swagger的资源 @Api(value="用户controller",tags={"用户操作接口"})

@ApiOperation()用于方法;表示一个http请求的操作

@ApiParam()用于方法,参数,字段说明; 表示对参数的添加元数据(说明或是否必填等)

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

@ApiModelProperty()用于方法,字段 ; 表示对model属性的说明或者数据操作更改

@ApiIgnore()用于类,方法,方法参数 ; 表示这个方法或者类被忽略

@ApiImplicitParam() 用于方法 ; 表示单独的请求参数

@ApiImplicitParams() 用于方法,包含多个 @ApiImplicitParam

相关文章
|
1月前
|
存储 API Go
学习gin-vue-admin之创建api和swagger
学习gin-vue-admin之创建api和swagger
|
10月前
|
Java API 网络架构
Spring Boot 学习研究笔记(六) -使用 Swagger 集成文档
Spring Boot 学习研究笔记(六) -使用 Swagger 集成文档
|
安全 API
集成Swagger 学习(二)
集成Swagger 学习(二)
68 0
|
前端开发 Java API
集成Swagger 学习(一)
集成Swagger 学习(一)
88 0
|
程序员 Spring API
spring cloud 学习(10) - 利用springfox集成swagger
对绝大多数程序员而言,写接口文档是一件痛苦的事情,相对文档,他们更愿意写代码。最理想的情况就是:代码即文档!服务开发完成后,部署上去文档就自动生成,没错,这就是springfox + swagger要解决的问题! swagger号称 THE WORLD'S MOST POPULAR API TOOLING。
1643 0
|
1月前
|
数据可视化 Java API
Spring Boot与Swagger的集成
Spring Boot与Swagger的集成
|
1月前
|
Java API 开发者
在Spring Boot中集成Swagger API文档
在Spring Boot中集成Swagger API文档
|
5天前
|
Java API Spring
springboot集成swagger
这篇文章介绍了如何在Spring Boot项目中集成Swagger 2.10.0来生成API文档,包括添加依赖、编写配置类、创建接口文档,并使用Knife4j美化Swagger界面。