欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

Spring Boot 集成Swagger框架

程序员文章站 2022-07-12 13:34:36
...

Spring Boot 集成Swagger框架

Swagger框架

1.啥是swagger
2.为啥要学swagger
3.swagger 有什么作用
4.swagger 效果图
5.swagger 代码加解释

啥是swagger

1.Swagger 是一款RESTFUL接口的文档在线自动生成和功能测试功能软件
2.Swagger 是一个规范和完整的框架,用于生成、描述、调用和可视化 RESTful 风格的 Web 服务
***简单点就是一个框架!

为啥要学swagger

主要: 方便,简单,明了,及时更新,维护修改强,还能在线测试 !
1.以本人(小白)为例:我为啥要学swagger,因为当时做个项目,这个项目是前后分离,前后分离就会出现问题,比如数据交互问题,当时不了解Api就随便用word文档写Api,让前台小姐姐接,好,还因为Api文档和前台小姐姐吵架发火,一路磕磕碰碰,终于写完后又出现维护(修改)问题,我当时就炸了,Api维护(修改)起来麻烦的要死,一下就全乱了!还不能及时更新。当时就头大了!

swagger 有什么作用

1.在前后台分离情况下,swagger是前后台最后一点羁绊。
2.swagger 可以在线生成模板和页面
3. swagger 可以在线测试Api接口

效果图

![Alt]Spring Boot 集成Swagger框架Spring Boot 集成Swagger框架
Spring Boot 集成Swagger框架

swagger 代码加注解

添加pox配置

// swagger
  <dependency>
            <groupId>io.springfox</groupId>
            <artifactId>springfox-swagger2</artifactId>
            <version>2.8.0</version>
        </dependency>
        <dependency>
            <groupId>io.springfox</groupId>
            <artifactId>springfox-swagger-ui</artifactId>
            <version>2.8.0</version>
        </dependency>

swagger配置类

		/**
 * 注释 用于学习
 *  搭建spring boot 项目
 *  集成sagger 框架
 *
 */
@Configuration
@EnableSwagger2
public class SaggerConfig {

    @Bean
    public Docket docket(){
        return new Docket(DocumentationType.SWAGGER_2)
                .groupName("视屏流量Api")
                .apiInfo(getApiInfo())
                .select()
                //设置basePackage会将包下的所有被@Api标记类的所有方法作为api
                .apis(RequestHandlerSelectors.basePackage("com.example.fiist.controller"))
                //只有标记了@ApiOperation的方法才会暴露出给swagger
                .apis(RequestHandlerSelectors.withMethodAnnotation(ApiOperation.class))
                .paths(PathSelectors.regex("/api/.*")).build();
    }

    private ApiInfo getApiInfo(){
        return new ApiInfoBuilder()
                .title("API接口文档")
                .description("swagger2 demo api")
                .termsOfServiceUrl("http://localhost/swagger-ui.html")
                .version("1.0")
                .build();
    }
}

解释:
@Configuration用于定义配置类,可替换xml配置文件,被注解的类内部包含有一个或多个被@Bean注解的方法,这些方法将会被AnnotationConfigApplicationContext或AnnotationConfigWebApplicationContext类进行扫描,并用于构建bean定义,初始化Spring容器。
.apis(RequestHandlerSelectors.basePackage(“你需要扫描的包”))

定义API接口

@RequestMapping("/api/test")
@RestController
@Api(value = "video API", tags = "video", description = "视频相关接口")
public class TestController extends ApiBaseAction {

    @ApiOperation(value = "获取视频流", notes = "获取视频流信息") //接口名称
    @ApiResponses({ //执行后返回执行状态加状态信息
            @ApiResponse(code = 200, message = "success"),
            @ApiResponse(code = 10001, message = "secret_key与token不符合"),
            @ApiResponse(code = 10002, message = "视频流类型错误", response = Exception.class),
            @ApiResponse(code = 500, message = "执行失败")
    })
    @PostMapping("/getVideo")//POST请求url
    public Object getVideo(@ApiParam(name = "secret_key", value = "秘钥", required = true)  @RequestParam String secret_key, //接取参数 赋值参数
                           @ApiParam(name = "token", value = "token", required = true) @RequestParam String token,
                           @ApiParam(name = "type", value = "流类型", required = true) @RequestParam String type,
                           @ApiParam(name = "json",value = "josn参数",required = true) @RequestParam String json){
        String data =  "{'type': " + type + ", 'url': 'rtmp://localhost/video', 'urlHD': 'rtmp://localhost/hd/video','json':"+json+"}";
        return this.toResponsSuccess(data);//自己分装的(ApiBaseAction )类中转json数据的方法
    }

    @ApiResponses({
            @ApiResponse(code = 200,message = "查询成功"),
            @ApiResponse(code = 500, message = "执行失败")
    })
    @ApiOperation(value = "获取视屏流集合数据",notes = "获取视屏流信息集")
    @GetMapping("/getVideoList")
    public Object getVideoList(){
        return this.toResponsMsgSuccess("返回视屏集合数据");
    }

    /**
     *  PutMapping和PostMapping 两则差别不大,
     *  如果是添加信息,倾向于用@PostMapping,如果是更新信息,倾向于用@PutMapping 如果是查询 倾向于@GetMapping
     *   @ApiImplicitParam用于描述方法的参数,标注在方法上,和@ApiParam功能一样,只是标注的位置不同而已
         * paramType:参数类型,即参数放在哪个地方
         * header–>请求参数的获取:@RequestHeader,参数放在请求头
         * query–>请求参数的获取:@RequestParam,参数追加在url后面
         * path(用于restful接口)–>请求参数的获取:@PathVariable
         * body 使用@RequestBody接收数据 POST有效,参数放在请求体中
     */
    @ApiOperation(value = "修改视频流", notes = "修改视频流信息")
    @ApiImplicitParams({
            @ApiImplicitParam(dataTypeClass = String.class, paramType = "header", name = "id", value = "id标识", required = true),
            @ApiImplicitParam(dataTypeClass = String.class, paramType = "query", name = "url", value = "高清视频流", required = true),
            @ApiImplicitParam(dataTypeClass = String.class, paramType = "path", name = "type", value = "视频流类型", required = true),
            @ApiImplicitParam(dataTypeClass = String.class, paramType = "body", name = "hdurl", value = "超清视频流", required = true)
    })
    @PutMapping("/update")
    public String updateVideo(@RequestHeader String id, @RequestParam String url, @PathVariable String type, @RequestBody String hdurl){
        return "{'id': " + id + ", 'url':" + url + ", 'type':" + type + ", 'hdurl':" + hdurl +"}";
    }
}

解释
RequestMapping :接口请求
RestController与Controller:区别都是控制层注解类,RestController这个返回数据是json格式
Api:用于扫描识别
ApiOperation:用于方法上注解,描述该方法干什么的
PostMapping:post请求
ApiResponses,ApiResponse容器,可以包含多个ApiResponse注解
ApiResponse,返回结果属性配置
code:返回结果的编码。
message:返回结果的说明。
response:返回结果对应的类。

最后访问 http://localhost:8080/swagger-ui.html 可以看到效果