> 文章列表 > Swagger教程

Swagger教程

Swagger教程

Swagger

目标

Swagger简介【了解】

Springboot整合swagger【掌握】

Swagger 常用注解【掌握】

一、Swagger简介

​ Swagger 是一系列 RESTful API 的工具,通过 Swagger 可以获得项目的⼀种交互式文档,客户端 SDK 的自 动生成等功能。

​ Swagger 的目标是为 REST APIs 定义一个标准的、与语⾔言无关的接口,使人和计算机在看不到源码或者看不到文档或者不能通过网络流量检测的情况下,能发现和理解各种服务的功能。当服务通过 Swagger 定义,消费者就能与远程的服务互动通过少量的实现逻辑。Swagger(丝袜哥)是世界上最流行的 API 表达工具。

二、Springboot整合swagger

​ 使用 Spring Boot 集成 Swagger 的理念是,使用用注解来标记出需要在 API 文档中展示的信息,Swagger 会根据项目中标记的注解来生成对应的 API 文档。Swagger 被号称世界上最流行的 API 工具,它提供了 API 管理的全套解决方案,API 文档管理需要考虑的因素基本都包含,这里将讲解最常用的定制内容。

1、添加swagger坐标

Spring Boot 集成 Swagger 3 很简单,需要引入依赖并做基础配置即可。

<dependency><groupId>io.springfox</groupId><artifactId>springfox-boot-starter</artifactId><version>3.0.0</version>
</dependency>

2、Swagger Helloword 实现

2.1、创建springboot项目

在启动类上加上@EnableOpenApi 注解 启用swagger api文档功能

@SpringBootApplication
@EnableOpenApi  //启动swagger api文档注解
public class SwaggerApplication {
}

2.2、写一个接口

@RestController
public class SwaggerController {@RequestMapping("/hello")public String getInfo(String par){return par;}
}

2.2、访问地址

http://localhost:8080/swagger-ui/index.html

在这里插入图片描述

三、常用的配置注解

​ Swagger 通过注解表明该接口会生成文档,包括接口名、请求方法、参数、返回信息等

1、Api 注解和 ApiOperation 注解

  • @Api

    使用在类上,表明是swagger资源,@API拥有两个属性:value、tags。

    生成的api文档会根据tags分类,直白的说就是这个controller中的所有接口生成的接口文档都会在tags这个list下;tags如果有多个值,会生成多个list,每个list都显示所有接口

    value的作用类似tags,但是不能有多个值

    语法:@Api(tags = "用户操作")或@Api(tags = {"用户操作","用户操作2"})
    
  • @ApiOperation

    使用于在方法上,表示一个http请求的操作

    语法:@ApiOperation(value = "", notes = "", response = )
    属性说明:value:方法说明标题notes:方法详细描述response:方法返回值类型
    

    案例:使用@Api和@ApiOperation生成api文档

    @RestController
    @Api(tags = {"hello请求","用户操作"})
    public class SwaggerController {@RequestMapping("/hello")@ApiOperation(value = "swagge请求",notes = "第一个swagger请求",response = String.class)public String getInfo(String param){return param;}
    }
    

2、ApiImplicitParams 注解和 ApiImplicitParam

@ApiImplicitParams 注解和 @ApiImplicitParam 用于对方法中的非对象参数(参数绑定到简单类型时使用。)进行说明

语法:
@ApiImplicitParams(value = {@ApiImplicitParam(name="", value = "", type = "", required = true, paramType = "", defaultValue  = "")
})属性说明:name:形参名称value:形参的说明文字type:形参类型required:该参数是否必须  true|falseparamType: 用于描述参数是以何种方式传递到 Controller 的,它的值常见有: path, query, body 和 header path 表示参数是『嵌在』路径中的,它和 @PathVariable 参数注解遥相呼应;query 表示参数是以 query string 的形式传递到后台的(无论是 get 请求携带在 url 中,还是 post 请求携带在请求体中),它和 @RequestParam 参数注解遥相呼应;header 表示参数是『藏在』请求头中传递到后台的,它和 @RequestHeader 参数注解遥相呼应的。form 不常用.defaultValue :参数默认值

注意:@ApiImplicitParam 的 name 属性要和 @RequestParam 或 @PathVariable 的 value 遥相呼应。

案例:使用@ApiImplicitParams注解和 @ApiImplicitParam 对方法参数进行说明

@RestController
@Api(tags = {"hello请求","用户操作"})
public class SwaggerController {@RequestMapping("/hello")@ApiOperation(value = "swagge请求",notes = "第一个swagger请求",response = String.class)@ApiImplicitParams(value ={@ApiImplicitParam(name="param",value = "参数名",type = "String",required = true,paramType = "query",defaultValue  = "1" )})public String getInfo(String param){return param;}
}

3、ApiModel注解和 ApiModelProperty

  • @ApiModel

    用在实体类上,表示对类进行说明,用于实体类中的参数接收说明。

    语法:@ApiModel("用户类")public class Users {}
    
  • @ApiModelProperty

    用于对实体类中的属性进行说明

    @ApiModel("用户类")
    @Data
    public class Users {@ApiModelProperty(value = "编码:主键")private Integer id;@ApiModelProperty(value = "用户名")private String username;@ApiModelProperty(value = "密码")private String password;}
    

4、ApiResponse 和 ApiResponses

@ApiResponses 注解和 @ApiResponse 标注在 Controller 的方法上,用来描述 HTTP 请求的响应

/*** 添加用户** @param user* @return*/@PostMapping("/add")@ApiOperation(value = "添加用户",notes = "添加用户信息",response = ResponseResult.class)@ApiResponses({ @ApiResponse(code = 200, message = "添加成功", response = ResponseResult.class),@ApiResponse(code = 500, message = "添加失败", response = ResponseResult.class) })public ResponseResult<Void> addUser(@RequestBody User user) {//获得生成的加密盐user.setSalt(SaltUtils.getSalt());int n = userService.addUser(user);if (n > 0) {return new ResponseResult<Void>(200, "添加成功");}return new ResponseResult<Void>(500, "添加失败");}

5、创建 SwaggerConfig 配置类

在 SwaggerConfig 中添加两个方法:(其中一个方法是为另一个方法作辅助的准备工作)

api()方法使用 @Bean,在启动时初始化,返回实例 Docket(Swagger API 摘要对象),这里需要注意的是 .apis(RequestHandlerSelectors.basePackage("xxx.yyy.zzz")) 指定需要扫描的包路路径,只有此路径下的 Controller 类才会自动生成 Swagger API 文档。

/*** Swagger配置类*/
@Configuration  //项目启动时加载此类
public class SwaggerConfig {@Beanpublic Docket api(){return new Docket(DocumentationType.OAS_30).apiInfo(apiInfo()).select()// 此处自行修改为自己的 Controller 包路径。.apis(RequestHandlerSelectors.basePackage("cn.woniu.controller")).paths(PathSelectors.any()).build();}public ApiInfo apiInfo(){return new ApiInfoBuilder().title("XXX 项目接口文挡").description("XXX Project Swagger2 UserService Interface")  //说明信息.termsOfServiceUrl("http://localhost:8080/swagger-ui/index.html") //文档生成的主页地址.version("1.0")  //文档版本.build();}
}

apiInfo()方法配置相对重要一些,主要配置页面展示的基本信息包括,标题、描述、版本、服务条款等,查看 ApiInfo 类的源码还会发现支持 license 等更多的配置

四、springsecurity整合swagger

4.1,配置放行的地址

  http.authorizeRequests().antMatchers( "/swagger-ui.html","/swagger-ui/*","/swagger-resources/**","/v2/api-docs","/v3/api-docs","/webjars/**").permitAll().anyRequest().authenticated();

4.2,替换UI

上面的整个过程已经完成了,但是生成的接口文档的页面,其实很多人不太喜欢,觉得不太符合国人的使用习惯,所有又有一些大神,提供了其他的UI测试页面。这个页面的使用还是比较广泛的。

访问地址:http://localhost:8080/doc.html

	<dependency><groupId>com.github.xiaoymin</groupId><artifactId>swagger-bootstrap-ui</artifactId><version>1.9.6</version></dependency>