百度360必应搜狗淘宝本站头条
当前位置:网站首页 > 编程网 > 正文

什么是Swagger(Api接口管理)?如何运用(代码实现)

yuyutoo 2024-10-12 01:50 7 浏览 0 评论

Swagger(Api管理)

主要应用于前后端分离的项目,实时更新最新API,降低集成风险。
RestFul Api文档在线自动生成工具=》Api文档与Api定义同步更新
直接运行,可以在线测试API接口
支持多种语言

#在项目中使用Swagger需要Springfox依赖;
& swagger2
& ui

SpringBoot集成Swagger

1、新建Springboot-web项目
2、在pom.xml中导入swagger依赖

<!--swagger2依赖 -->
        <!--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>
1234567891011121314

3、编写一个可访问控制器接口备用
4、配置swagger(Config)

Docket:摘要对象,通过对象配置描述文件的信息。 apiInfo:设置描述文件中 info。参数类型 ApiInfo
select():返回 ApiSelectorBuilder 对象,通过对象调用 build()可以 创建 Docket 对象

创建配置类测试运行

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

1)尝试访问 http://localhost:8080/swagger-ui.html可见如下页面


2)配置Swagger

package com.autorestapi.swagger.config;

import io.swagger.annotations.Api;
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 org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
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;

import java.util.ArrayList;
@Configuration
@EnableSwagger2     //开启Swagger2
public class SwaggerConfig {

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

        //设置要启动swagger的环境
        Profiles profiles = Profiles.of("dev","test");
        //判断当前环境是否处在启动swagger的环境中 Environment系统环境变量
        boolean flag = environment.acceptsProfiles(profiles);

        return new Docket(DocumentationType.SWAGGER_2)
                /**
                 *配置Swagger信息
                 */
                .apiInfo(apiInfo())
                .groupName("json-lu")//swagger分组,一个Docket实例就是一个分组,默认是default
                /**
                 * 配置是否启动swagger
                 *  如果为false,Swagger在浏览器中不能访问
                 */
                .enable(flag)//根据系统环境决定是否启动swagger
                .select()
                /**
                 * RequestHandlerSelectors,配置要扫描接口的方式
                 *      basePackage("包路径"):指定要扫描的包
                 *      any():扫描全部
                 *      none():不扫描
                 *      withClassAnnotation:扫描类上的注解,参数是一个注解的反射对象
                 *      withMethodAnnotation:扫描方法上的注解
                 */
                .apis(RequestHandlerSelectors.basePackage("com.autorestapi.swagger.controller"))
                /**
                 *  过滤接口路径
                 *      PathSelectors,配置扫描接口中需要被过滤掉的路径
                 *      ant("访问路径"):过滤该访问路径的接口
                 *      any():过滤全部
                 *      none():不过滤
                 *      regex(正则):按照正则表达式过滤路径
                 */
                .paths(PathSelectors.ant("/user/**"))
                .build();
    }

    //配置Swagger信息
    private ApiInfo apiInfo(){
        //作者信息
        Contact contact = new Contact("json-lu", "https://gitee.com/json-lu/", "freedStyle@163.com");
        return  new ApiInfo("My Swagger接口文档",//title
                "first Swagger",//描述
                "1.0",
                "https://gitee.com/json-lu/",
                contact,
                "Apache 2.0",
                "http://www.apache.org/licenses/LICENSE-2.0",
                new ArrayList());
    }

}

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182

5、配置api文档的分组


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

 @Bean
    public Docket docket1(){
        return new Docket(DocumentationType.SWAGGER_2).groupName("A");//A分组
    }

    @Bean
    public Docket docket2(){
        return new Docket(DocumentationType.SWAGGER_2).groupName("B");//B分组
    }

    @Bean
    public Docket docket3(){
        return new Docket(DocumentationType.SWAGGER_2).groupName("C");//C分组
    }
1234567891011121314

常用注解

Model层:
@ApiModel("实体类注释")
@ApiModelProperty("属性名注释")

package com.autorestapi.swagger.pojo;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;
@ApiModel("用户实体类")
@Data
public class User {

    @ApiModelProperty("用户名")
    private String username;
    @ApiModelProperty("密码")
    private String password;
}
12345678910111213

Controller层:
@Api(tags="controller描述")
@ApiOperation("方法描述")
@ApiParam("参数描述")

package com.autorestapi.swagger.controller;

import com.autorestapi.swagger.pojo.User;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.web.bind.annotation.*;
@Api(tags = "Hello控制类")
@RestController
public class HelloController {

    /**
     * 一个项目一定有一个/error请求(任意请求路径)
     *  所以有两个请求路径 /error /hello
     * @return
     */
    @GetMapping(value = "/user/hello")
    @ApiOperation(value = "hello方法")
    public String hello(){
        return "hello";
    }

    /**
     * ApiOperation参数
     * value:方法描述
     * httpMethod:方法请求类型
     * notes:方法注释
     * tags:方法作用(标签)
     * @return
     */
    @GetMapping(value = "/user")
    @ApiOperation(value = "user方法",httpMethod = "GET",notes = "hello方法返回hello")
    public User getUser(){
        return new User();
    }

    @GetMapping(value = "/user/hello2")
    @ApiOperation("带参数hello方法")
    public String hello(@ApiParam("用户名") String username){
        return "hello"+username;
    }

    @PostMapping(value = "/user/hello3")
    @ApiOperation("带参数hello3方法")
    public String hello2(@ApiParam("用户名") @RequestBody String username){
        return "hello"+username;
    }
}
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748

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


相关推荐

.NET 奇葩问题调试经历之3——使用了grpc通讯类库后,内存一直增长......

...

全局和隐式 using 指令详解(全局命令)

1.什么是全局和隐式using?在.NET6及更高版本中,Microsoft引入了...

请停止微服务,做好单体的模块化才是王道:Spring Modulith介绍

1、介绍模块化单体是一种架构风格,代码是根据模块的概念构成的。对于许多组织而言,模块化单体可能是一个很好的选择。它有助于保持一定程度的独立性,这有助于我们在需要的时候轻松过渡到微服务架构。Spri...

ASP.NET程序集引用之痛:版本冲突、依赖地狱等解析与实战

我是一位多年后端经验的工程师,其中前几年用ASP.NET...

.NET AOT 详解(.net 6 aot)

简介AOT(Ahead-Of-TimeCompilation)是一种将代码直接编译为机器码的技术,与传统的...

一款基于Yii2开发的免费商城系统(一款基于yii2开发的免费商城系统是什么)

哈喽,我是老鱼,一名致力于在技术道路上的终身学习者、实践者、分享者!...

asar归档解包(游戏arc文件解包)

要学习Electron逆向,首先要有一个Electron开发的程序的发布的包,这里就以其官方的electron-quick-start作为例子来进行一下逆向的过程。...

在PyCharm 中免费集成Amazon CodeWhisperer

CodeWhisperer是Amazon发布的一款免费的AI编程辅助小工具,可在你的集成开发环境(IDE)中生成实时单行或全函数代码建议,帮助你快速构建软件。简单来说,AmazonCodeWhi...

2014年最优秀JavaScript编辑器大盘点

1.WebstormWebStorm是一种轻量级的、功能强大的IDE,为Node.js复杂的客户端开发和服务器端开发提供完美的解决方案。WebStorm的智能代码编辑器支持JavaScript,...

基于springboot、tio、oauth2.0前端vuede 超轻量级聊天软件分享

项目简介:基于JS的超轻量级聊天软件。前端:vue、iview、electron实现的PC桌面版聊天程序,主要适用于私有云项目内部聊天,企业内部管理通讯等功能,主要通讯协议websocket。支持...

JetBrains Toolbox推出全新产品订阅授权模式

捷克知名软件开发公司JetBrains最为人所熟知的产品是Java编程语言开发撰写时所用的集成开发环境IntelliJIDEA,相信很多开发者都有所了解。而近期自2015年11月2日起,JetBr...

idea最新激活jetbrains-agent.jar包,亲测有效

这里分享一个2019.3.3版本的jetbrains-agent.jar,亲测有效,在网上找了很多都不能使用,终于找到一个可以使用的了,这里分享一下具体激活步骤,此方法适用于Jebrains家所有产品...

CountDownTimer的理解(countdowntomars)

CountDownTimer是android开发常用的计时类,按照注释中的说明使用方法如下:kotlin:object:CountDownTimer(30000,1000){...

反射为什么性能会很慢?(反射时为什么会越来越长)

1.背景前段时间维护一个5、6年前的项目,项目总是在某些功能使用上不尽人意,性能上总是差一些,仔细过了一下代码发现使用了不少封装好的工具类,工具类里面用了好多的反射,反射会影响到执行效率吗?盲猜了一...

btrace 开源!基于 Systrace 高性能 Trace 工具

介绍btrace(又名RheaTrace)是抖音基础技术团队自研的一款高性能AndroidTrace工具,它基于Systrace实现,并针对Systrace不足之处加以改进,核心改进...

取消回复欢迎 发表评论: