• 【转】Swagger详解(SpringBoot+Swagger集成)


    Swagger-API文档接口引擎
    Swagger是什么

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

    在项目开发中,根据业务代码自动生成API文档,给前端提供在线测试,自动显示JSON格式,方便了后端与前端的沟通与调试成本。

    Swagger有一个缺点就是侵入性模式,必须配置在具体的代码里。
    Swagger使用(SpringBoot+Swagger集成)

    新建Maven项目

    第一种方式:使用第三方依赖

    1.在pom.xml文件中添加第三方swagger依赖

        <dependency>
            <groupId>com.spring4all</groupId>
            <artifactId>swagger-spring-boot-starter</artifactId>
            <version>1.7.0.RELEASE</version>
        </dependency>

    2、在Spring Boot项目的启动类上添加@EnableSwagger2,启动Swagger
    3、https://github.com/SpringForAll/spring-boot-starter-swagger,GitHub上这个swagger依赖实现的项目,里面有详细的讲解。

    第二种方式:使用官方依赖

    1.在pom.xml文件中添加swagger相关依赖

        <dependency>
                <groupId>io.springfox</groupId>
                <artifactId>springfox-swagger2</artifactId>
                <version>2.2.2</version>
        </dependency>
        <dependency>
                <groupId>io.springfox</groupId>
                <artifactId>springfox-swagger-ui</artifactId>
                <version>2.2.2</version>
        </dependency>
        <dependency>
                <groupId>org.codehaus.jackson</groupId>
                <artifactId>jackson-core-asl</artifactId>
                <version>1.9.13</version>
        </dependency>

     第一个是API获取的包

    第二是官方给出的一个ui界面,这个界面可以自定义,默认是官方的

    第三个是测试数据以JSON格式返回的依赖包

    2.配置Swagger

    新建Swagger配置类,需要特别注意的是Swagger scan base package,这是扫描注解的配置,即你的API接口位置,对前端提供服务接口的位置。

        package com.example.demo.config;
        @Configuration
        @EnableSwagger2
        public class SwaggerConfig {
            private ApiInfo apiInfo() {
                return new ApiInfoBuilder().title("API接口文档")
                        .description("用户信息管理")
                        .version("1.0.0")
                        .build();
            }
            @Bean
            public Docket createRestApi() {
                return new Docket(DocumentationType.SWAGGER_2)
                        .apiInfo(apiInfo())
                        .select()
                        .apis(RequestHandlerSelectors.basePackage("com.example.demo.controller")) //这里写的是API接口所在的包位置
         
                        .paths(PathSelectors.any())
                        .build();
            }
        }

    3.简单写个Dao和User实体类

        package com.example.demo.dao;
         
        import com.example.demo.entity.User;
        public interface UserDao {
            User findById(Integer id);
            User findByName(String name);
         
        }
         
         
         
        public class User {
            int id;//用户ID
            String name;//姓名
         
            public void setId(int id){
                
                this.id=id;
            }
            public int getId(){
                
                return id;
            }
            public void setName(String name){
                this.name=name;
            }
            public String getName(){
                
                return name;
            }

    4.撰写Controller(UserController)

        @RestController
        @RequestMapping("/user")
        @Api(value = "用户信息管理")
        public class UserController {
        UserDao userDao;
                
            @RequestMapping(method = RequestMethod.POST,value = "/userById")
            @ApiOperation(value = "获取用户信息", notes = "通过用户ID获取用户信息")
            public Object findById(@ApiParam(value = "用户ID",required = true) int id){
                return userDao.findById(id);
            }
         
            @RequestMapping(method = RequestMethod.POST,value = "/userByName")
            @ApiOperation(value = "获取用户信息", notes = "通过用户姓名获取用户信息")
            public Object findByName(@ApiParam(value = "用户姓名",required = true) String  name){
            return userDao.findByName(name);
            }
         
        }

    5.设定访问API文档的路由

    在配置文件中,application.yml中声明:

    springfox.documentation.swagger.v2.path: /api-docs

    这个path就是json的访问request mapping.可以自定义,防止与自身代码冲突。

    API doc的显示路由是:http://localhost:8080/swagger-ui.html

     
    Swagger常用注解

    1、Api标记

    Api 用在类上,说明该类的作用。可以标记一个Controller类做为swagger 文档资源,使用方式:
    @Api(value = "/user", description = "Operations about user")

    2、ApiOperation标记

    ApiOperation:用在方法上,说明方法的作用,每一个url资源的定义,使用方式:

    @ApiOperation(

              value = "Find purchase order by ID",

              notes = "For valid response try integer IDs with value <= 5 or > 10. Other values will generated exceptions",

              response = Order,

              tags = {"Pet Store"})

    3、ApiParam标记

    ApiParam请求属性,使用方式:

    public ResponseEntity<User> createUser(@RequestBody @ApiParam(value = "Created user object", required = true)  User user)

    4.  ApiResponse

    ApiResponse:响应配置,使用方式:
    @ApiResponse(code = 400, message = "Invalid user supplied")

    5.  ApiResponses

    ApiResponses:响应集配置,使用方式:
    @ApiResponses({ @ApiResponse(code = 400, message = "Invalid Order") })

    6.  ResponseHeader

    响应头设置,使用方法
    @ResponseHeader(name="head1",description="response head conf")

    @Api()用于类;
    表示标识这个类是swagger的资源
    @ApiOperation()用于方法;
    表示一个http请求的操作
    @ApiParam()用于方法,参数,字段说明;
    表示对参数的添加元数据(说明或是否必填等)
    @ApiModel()用于类
    表示对类进行说明,用于参数用实体类接收
    @ApiModelProperty()用于方法,字段
    表示对model属性的说明或者数据操作更改
    @ApiIgnore()用于类,方法,方法参数
    表示这个方法或者类被忽略
     @ApiImplicitParam() 用于方法
    表示单独的请求参数
     @ApiImplicitParams() 用于方法,包含多个 @ApiImplicitParam
     @Api()
    用于类;表示标识这个类是swagger的资源
    tags–表示说明
    value–也是说明,可以使用tags替代
    但是tags如果有多个值,会生成多个list

    @Api(value="用户controller",tags={"用户操作接口"})

    @RestController

    public class UserController {

    }

    @ApiOperation() 用于方法;表示一个http请求的操作
    value用于方法描述
    notes用于提示内容
    tags可以重新分组(视情况而用)
    @ApiParam() 用于方法,参数,字段说明;表示对参数的添加元数据(说明或是否必填等)
    name–参数名
    value–参数说明
    required–是否必填

    @ApiModel()用于类 ;表示对类进行说明,用于参数用实体类接收
    value–表示对象名
    description–描述
    都可省略
    @ApiModelProperty()用于方法,字段; 表示对model属性的说明或者数据操作更改
    value–字段说明
    name–重写属性名字
    dataType–重写属性类型
    required–是否必填
    example–举例说明
    hidden–隐藏

    @ApiIgnore()用于类或者方法上,可以不被swagger显示在页面上
    比较简单, 这里不做举例

    @ApiImplicitParam() 用于方法
    表示单独的请求参数
    @ApiImplicitParams() 用于方法,包含多个 @ApiImplicitParam
    name–参数ming
    value–参数说明
    dataType–数据类型
    paramType–参数类型
    example–举例说明

    --------------------------------->基础篇---------------------
    版权声明:本文为CSDN博主「ai_miracle」的原创文章,遵循CC 4.0 by-sa版权协议,转载请附上原文出处链接及本声明。
    原文链接:https://blog.csdn.net/ai_miracle/article/details/82709949

  • 相关阅读:
    快速傅里叶变换(FFT)
    【BZOJ】1005: [HNOI2008]明明的烦恼(prufer编码+特殊的技巧)
    【BZOJ】1030: [JSOI2007]文本生成器(递推+ac自动机)
    cf490 C. Hacking Cypher(无语)
    高精度模板2(带符号压位加减乘除开方封包)
    【BZOJ】1004: [HNOI2008]Cards(置换群+polya+burnside)
    【BZOJ】1500: [NOI2005]维修数列(splay+变态题)
    【BZOJ】1064: [Noi2008]假面舞会(判环+gcd+特殊的技巧)
    【BZOJ】1052: [HAOI2007]覆盖问题(贪心)
    【BZOJ】1028: [JSOI2007]麻将(贪心+暴力)
  • 原文地址:https://www.cnblogs.com/wangwangfei/p/11346545.html
Copyright © 2020-2023  润新知