springboot-swagger

作者: lconcise | 来源:发表于2018-12-03 22:34 被阅读16次

    喜欢Swagger,就是在前后端分离中,可以及时的在线同步更新api文档方便自己进行功能测试
    当然这是只是强大的Swagger的一部分,下面我带着大家了解下Swagger,同时做一个spingboot-swagger的一个Demo,供大家参考。

    什么是 Swagger

    Swagger 是一个规范和完整的框架,用于生成、描述、调用和可视化 RESTful 风格的 Web 服务。总体目标是使客户端和文件系统作为服务器以同样的速度来更新。文件的方法,参数和模型紧密集成到服务器端的代码,允许API来始终保持同步

    下面从官方的角度介绍下Swagger,这部分你也可以直接跳过。


    The Best APIs are Built with Swagger Tools

    最好的api是用Swagger构建的

    官网地址:https://swagger.io/

    image.png

    Swagger 主要包含以下5部分组成.

    • Design - API Design

      API Design
      Design is the foundation of your API development. Swagger makes API design a breeze, with easy-to-use tools for developers, architects, and product owners.

      设计是API开发的基础。Swagger使API设计变得轻而易举,为开发人员、架构师和产品所有者提供了易于使 用的工具。

    • Build - API Development

      API Development
      Protocols, error handling, and code modularity are just some of the questions your teams need to address before building a great API. Swagger provides tools for quickly prototyping and building your API’s functionality.

      协议、错误处理和代码模块化只是团队在构建优秀API之前需要解决的一些问题。Swagger提供了快速原型化和构建API功能的工具。

    • Document - API Documentation

      API Documentation
      Swagger takes the manual work out of API documentation, with a range of solutions for generating, visualizing, and maintaining API docs.

    Swagger从API文档中提取手工工作,并提供了一系列用于生成、可视化和维护API文档的解决方案。

    • Test - API Testing

      API Testing
      Start your functional, security, and performance testing right from the OpenAPI Spec. Swagger tooling and the ReadyAPI platform make it easy to rapidly create, manage, & execute API tests in your pipeline.

    从OpenAPI规范开始您的功能、安全性和性能测试。Swagger工具和ReadyAPI平台使得在您的管道中快速创建、管理和执行API测试变得容易。

    • Standardize - Governance and Standardization

      Governance and Standardization
      People and processes make up a successful API program. Efficiently managing these efforts makes for good governance. Whether you have a team of five or five hundred, Swagger can help.

    人员和流程构成了一个成功的API程序。有效地管理这些工作有助于良好的治理。不管你的团队是5人还是500人,Swagger都能帮助到你。


    快速上手

    Spring Boot 集成 Swagger 2.X 很简单,需要引入依赖并做基础配置就可以了。

    1. 添加依赖

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

    2. 添加配置类SwaggerConfig

    /**
     * SwaggerConfig.
     */
    @Configuration
    @EnableSwagger2
    public class SwaggerConfig {
    
        @Bean
        public Docket createRestApi() {
            return new Docket(DocumentationType.SWAGGER_2)
                    .apiInfo(apiInfo())
                    .select()
                    .apis(RequestHandlerSelectors.basePackage("top.lconcise.controller"))
                    .paths(PathSelectors.any())
                    .build();
        }
    
        private ApiInfo apiInfo() {
            return new ApiInfoBuilder()
                    .title("SpringBoot-Swagger api文档")
                    .description("")
                    .termsOfServiceUrl("https://www.jianshu.com/u/ce4cf486d279")
                    .version("1.0")
                    .build();
        }
    }
    
    • @Configuration 配置类,启动时加载此类
    • @EnabledSwagger2 标识项目启动 SwaggerApi 文档
    • ApiInfo 这个类时Swagger 页面展示的一些基础信息
    • RequestHandlerSelectors.basePackage("top.lconcise.controller") 这里的top.lconcise.controller 是扫描包的路径

    3.编写一个controller 类

    package top.lconcise.controller;
    
    import io.swagger.annotations.Api;
    import io.swagger.annotations.ApiOperation;
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.web.bind.annotation.*;
    import top.lconcise.bus.entity.User;
    import top.lconcise.bus.service.UserService;
    import top.lconcise.view.Message;
    
    @Api(value = "用户相关操作", tags = "用户相关操作")
    @RestController
    @RequestMapping("/users")
    public class UserController {
    
        @Autowired
        private UserService userService;
    
        @ApiOperation("创建用户")
        @PostMapping
        public Message<String> create(@RequestBody User bean) {
            return userService.create(bean);
        }
    
        @ApiOperation("修改用户")
        @PutMapping
        public Message<String> put(@RequestBody User bean) {
            return userService.update(bean);
        }
    
        @ApiOperation("获取所有用户")
        @GetMapping
        public Message findAll() {
            return userService.findAll();
        }
    
        @ApiOperation("根据id删除用户")
        @DeleteMapping(value = "/{id}")
        public Message deleteById(@PathVariable("id") Long id) {
            return userService.deletedById(id);
        }
    }
    

    4. 启动项目 访问 http://127.0.0.1:8080/swagger-ui.html
    效果如下图

    image.png

    就可以很清楚看到用户的相关接口,并进行接口测试。

    image.png image.png image.png

    点击这里下载源码

    相关文章

      网友评论

        本文标题:springboot-swagger

        本文链接:https://www.haomeiwen.com/subject/zafgqqtx.html