• SpringBoot项目中使用Swagger2,及其详细介绍注解


    SpringBoot项目中使用Swagger2,及其详细介绍注解

    什么是swagger2

    编写和维护接口文档是每个程序员的职责,根据Swagger2可以快速帮助我们编写最新的API接口文档,再也不用担心开会前仍忙于整理各种资料了,间接提升了团队开发的沟通效率。

    1、swagger2的配置

    1.1、引入Swagger2依赖

            
            <dependency>
                <groupId>io.springfoxgroupId>
                <artifactId>springfox-swagger2artifactId>
                <version>2.7.0version>
            dependency>
            
            <dependency>
                <groupId>io.springfoxgroupId>
                <artifactId>springfox-swagger-uiartifactId>
                <version>2.7.0version>
            dependency>
            
            <dependency>
                <groupId>com.github.xiaoymingroupId>
                <artifactId>knife4j-spring-boot-starterartifactId>
                <version>2.0.4version>
            dependency>
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18

    1.2、编写SwaggerConfig配置文件

    package com.melody.rest.config;
    
    import org.springframework.context.annotation.Bean;
    import org.springframework.context.annotation.Configuration;
    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;
    
    /**
     * @ClassName: SwaggerConfig
     * @Description: Swagger配置了类
     * @Author: liu-hao
     * @Date: 2020-12-10 10:18
     * @Version: 1.0
     **/
    @Configuration
    @EnableSwagger2
    public class SwaggerConfig {
        // api接口包扫描路径
        public static final String SWAGGER_SCAN_BASE_PACKAGE = "com.melody.rest.restcontroller";
        // 接口文档版本
        public static final String VERSION = "1.0.0";
    
        @Bean
        public Docket api() {
            return new Docket(DocumentationType.SWAGGER_2)
                    //用于分组功能,也可以不配置
                    .groupName("eleprice-service")
                    //注册整体api信息
                    .apiInfo(apiInfo())
                    //swagger功能是否启用,可以通过配置设置,也可以先写死
                    .enable(true)
                    .select()
                    .apis(RequestHandlerSelectors.basePackage(SWAGGER_SCAN_BASE_PACKAGE))
                    .paths(PathSelectors.any())
                    .build();
        }
    
        private ApiInfo apiInfo() {
            return new ApiInfoBuilder().title("学习系统")
                    .description("接口文档")
                    .contact(new Contact("张三", "http://liushili.icu", "xxxxx@163.com"))
                    .version(VERSION)
                    .build();
        }
    }
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45
    • 46
    • 47
    • 48
    • 49
    • 50
    • 51
    • 52

    注意:更改成项目中的controller

    在这里插入图片描述

    1.3、配置类及其参数说明

    (1)创建Docker类型的对象,并使用spring容器管理。Docker是Swagger中的全局配置对象

    DocumentationType.SWAGGER_2:给Docket一个类对象,知道是那一个版本的

    apiInfo():API文档的描述信息,参数是一个ApiInfo类对象,使用bulid()构建器来创建

    private ApiInfo apiInfo() {
           return new ApiInfoBuilder()
                   .title("平台接口 v1.0")
                   .description("平台接口")
                   .contact(contact)
                   .version("1.0")
                   .build();
       }
    12345678
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9

    image-20220813230037907

    (2)contact():配置swagger文档的主体内容,里面填写也是一个类对象,类对象最多可以三个参数,发布者名称,文档发布者的网站url地址(企业网站),文档发布者的电子邮箱地址

    private Contact contact = new Contact("NIUA","localhost:8080/swagger-ui.html", "1053288979@qq.com");
    1
    
    • 1
    • 2

    title():标题 description():描述信息 .version():版本信息

    对应如下内容

    select():获取Docker中的选择器,返回ApiSelectorBuilder。构建选择器。如扫描什么包的注解

    apis():后面是RequestHandlerSelectors的类下的(Predicate)规则,规定扫描那些包的注解,默认是启动类及其子包下的注解

    RequestHandlerSelectors类下有几个静态方法(举例三个)

    basePackage():后面填写包名的具体地址,会扫描改包及其子包的注解

    docker.apis(RequestHandlerSelectors.basePackage("com.xxx"))
    1
    
    • 1
    • 2

    any():为任何接口生成API文档

    none():任何接口都不生成接口文档

    path():使用正则表达式,约束生成Api文档的路径地址,后面填写过滤(通过)的路径

    //过滤掉admin路径下的所有页面
    .paths(Predicates.not(PathSelectors.regex("/admin/.*")))
    //过滤掉所有error或error.*页面
    .paths(Predicates.not(PathSelectors.regex("/error.*")))
    
    //所有error或error.*页面或者admin路径下的所有页面都支持(or任意满足起一就通过)
    .paths(Predicates.or(PathSelectors.regex("/error.*"),PathSelectors.regex("/admin/.*")))
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7

    2、swagger2 注解整体说明

    2.1、请求类的描述

    注解说明
    @Api对请求类的说明

    2.2、方法和方法参数的描述

    注解说明
    @ApiOperation方法的说明
    @ApiImplicitParams方法参数的说明;
    @ApiImplicitParam用于指定单个参数的说明。

    2.3、方法的响应状态的描述

    注解说明
    @ApiResponses方法返回值的说明 ;
    @ApiResponse用于指定单个参数的说明。

    2.4、对象的描述

    注解说明
    @ApiModel用在JavaBean类上,说明JavaBean的 整体用途
    @ApiModelProperty用在JavaBean类的属性上面,说明此属性的的含议

    3、请求类的描述

    3.1、@Api:请求类的说明

    @Api:放在 请求的类上。与 @Controller 并列,说明类的作用,如用户模块,订单类等。
    	tags="说明该类的作用"
    	value="该参数没什么意义,所以不需要配置"
    123
    
    • 1
    • 2
    • 3
    • 4

    3.2、示例:

    @Api(tags="订单模块")
    @Controller
    public class OrderController {
    
    }
    12345
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6

    @Api 其它属性配置:

    属性名称备注
    valueurl的路径值
    tags如果设置这个值、value的值会被覆盖
    description对api资源的描述
    basePath基本路径
    position如果配置多个Api 想改变显示的顺序位置
    produces如, “application/json, application/xml”
    consumes如, “application/json, application/xml”
    protocols协议类型,如: http, https, ws, wss.
    authorizations高级特性认证时配置
    hidden配置为true ,将在文档中隐藏

    4、方法和方法参数的描述

    4.1、@ApiOperation:方法的说明

    @ApiOperation"用在请求的方法上,说明方法的作用"
    	value="说明方法的作用"
    	notes="方法的备注说明"
    123
    
    • 1
    • 2
    • 3
    • 4

    4.2、@ApiImplicitParams、@ApiImplicitParam:方法参数的说明

    @ApiImplicitParams:用在请求的方法上,包含一组参数说明
    	@ApiImplicitParam:对单个参数的说明	    
    	    name:参数名
    	    value:参数的说明、描述
    	    required:参数是否必须必填
    	    paramType:参数放在哪个地方
    	        · query --> 请求参数的获取:@RequestParam
    	        · header --> 请求参数的获取:@RequestHeader	      
    	        · path(用于restful接口)--> 请求参数的获取:@PathVariable
    	        · body(请求体)-->  @RequestBody User user
    	        · form(普通表单提交)	   
    	    dataType:参数类型,默认String,其它值dataType="Integer"	   
    	    defaultValue:参数的默认值
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13

    4.3、示列:

    @Api(tags="用户模块")
    @Controller
    public class UserController {
    
    	@ApiOperation(value="用户登录",notes="这里是备注")
    	@ApiImplicitParams({
    		@ApiImplicitParam(name="mobile",value="手机号",required=true,paramType="form"),
    		@ApiImplicitParam(name="password",value="密码",required=true,paramType="form"),
    		@ApiImplicitParam(name="age",value="年龄",required=true,paramType="form",dataType="Integer")
    	})
    	@PostMapping("/login")
    	public JsonResult login(@RequestParam String mobile, @RequestParam String password,	@RequestParam Integer age){
    		//...
    	    return JsonResult.ok(map);
    	}
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16

    5、对象的描述

    5.1、@ApiModel:对象的整体说明

    @ApiModel 经常用于请求的入参对象和 响应返回值对象的描述。

    1. 入参是对象,即 @RequestBody 时, 用于封装请求(包括数据的各种校验)数据;
    2. 返回值是对象,即 @ResponseBody 时,用于返回值对象的描述。
    @ApiModel(description = "用户登录")
    public class UserLoginVO  implements  Serializable {
    
    }
    1234
    
    • 1
    • 2
    • 3
    • 4
    • 5

    5.2、@ApiModelProperty 对象中每个参数的说明

    @ApiModelProperty 用于每个属性上面,说明属生的含义。

    @ApiModel
    public class UserLoginVO  implements  Serializable {
    
    	@ApiModelProperty(value = "用户名",required=true)	
    	private String username;	
    }
    123456
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7

    5.3、示例:

    入参是对象,即 @RequestBody 时, 用于封装请求
    @ApiModel(description = "用户登录")
    public class UserLoginVO implements Serializable {
    
    	private static final long serialVersionUID = 1L;
    
    	@ApiModelProperty(value = "用户名",required=true)	
    	private String username;
    
    	@ApiModelProperty(value = "密码",required=true)	
    	private String password;
    	
    	// getter/setter省略
    }
    ApiModel(description = "用户登录")
    public class UserLoginVO implements Serializable {
    
    	private static final long serialVersionUID = 1L;
    
    	@ApiModelProperty(value = "用户名",required=true)	
    	private String username;
    
    	@ApiModelProperty(value = "密码",required=true)	
    	private String password;
    	
    	// getter/setter省略
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
  • 相关阅读:
    嵌入式设备驱动开发
    多尺度结构元素形态学边缘检测算法的研究-含Matlab代码
    使用labelme自制coco格式数据集
    软件测试框架的面试题讲解
    Git - 标签管理
    python集成乐玩插件
    C++贪心算法之最小新整数
    加密,各种加密,耙梳加密算法(Encryption)种类以及开发场景中的运用(Python3.10)
    5. hdfs的界面详解
    qt学习之旅--MinGW编译FFmpeg(32bit)
  • 原文地址:https://blog.csdn.net/qq_45830276/article/details/126556165