Spring boot 接入swagger以及使用

2020-12-24  本文已影响0人  NoelI

Springboot 集成Swagger 2(springfox)

1、集成

导入依赖

Springfox Swagger2:

<!-- https://mvnrepository.com/artifact/io.springfox/springfox-swagger2 -->
<dependency>
    <groupId>io.springfox</groupId>
    <artifactId>springfox-swagger2</artifactId>
    <version>3.0.0</version>
</dependency>

Springfox Swagger UI:

<!-- https://mvnrepository.com/artifact/io.springfox/springfox-swagger-ui -->
<dependency>
    <groupId>io.springfox</groupId>
    <artifactId>springfox-swagger-ui</artifactId>
    <version>3.0.0</version>
</dependency>

配置swagger

@Configuration
@EnableSwagger2
public class SwaggerConfig{}

创建一个以上一个类配置swagger即可。

默认效果

访问界面:IP:port/swagger-ui.html

image-20201125162617615.png

2、配置

在以上配置类中添加方法:

//配置swagger的Docket的Bean实例
@Bean
public Docket docket(){
    return new Docket(DocumentationType.SWAGGER_2).apiInfo(this.apiInfo());
}

//自定义swagger信息
private ApiInfo apiInfo(){
    Contact contact = new Contact("name","url","email");
    return new ApiInfo("title","description","version","termsOfServiceUrl",contact,"license",licenseUrl,new ArrayList());
}

3、配置扫描接口

项目中并不需要swagger将整个项目的所有类暴露出去,通过以上配置的Bean实例,设置swagger关注并显示的接口,以及是否开启使用:

return new Docket(DocumentationType.SWAGGER_2)
    .apiInfo(apiInfo())
    .enable(false)//false时,浏览器不能访问,默认为true
    .select()
    //RequestHandlerSelect,配置要扫描接口的方式
    //basePackage("包路径"):指定要扫描的包
    //any():全部扫描
    //none():不扫描
    //withClassAnnotation():扫描类上有指定的类注解的类,参数是一个类注解,如"RestContrller.class"
    //withMethodAnnotation():扫描方法上有指定的注解的方法,参数如"GetMapping.class"
    .api(RequestHandlerSelectors.basePackage("com.noel.swagger.controller"))
    //paths():过滤某些路径,参数为正则匹配参数
    .paths(PathSelectors.ant("/omit/**"))
    .build();

只希望在开发环境中使用swagger,但是生产环境不使用:

@Bean
public Docket docket(Environment environment){
    //dev: application-dev.yml or application-anotherEnv.yml 或者类似的properties配置文件
    //如果允许时加载了指定的环境,则返回true
    Profiles profiles = Profiles.of("dev","anotherEnv");
    Boolean isSwaggerOn = environment.acceptsProfiles(profiles);
    return new Docket(DocumentationType.SWAGGER_2)
        .apiInfo(this.apiInfo())
        .enable(isSwaggerOn);
}

配置API文档分组:

.group("groupName")

配置多个分组:

@Bean
public Docket docketGroupA(){
    return new Docket(DocumentationType.SWAGGER_2).groupName("A");
}
@Bean
public Docket docketGroupB(){
    return new Docket(DocumentationType.SWAGGER_2).groupName("B");
}
@Bean
public Docket docketGroupB(){
    return new Docket(DocumentationType.SWAGGER_2).groupName("C");
}

在配置类中,一个Docket Bean实例,对应一个swagger分组。

4、常用注解

4.1、接口类的注解

注解名称 说明
@Api(tags="模块说明") 作用在API接口类Controller上,说明该类的用途
@ApiOperation("APPI接口说明") 在API接口方法上进行说明
@ApiImplicitParams 接口的参数说明,用于对多个参数进行说明
@ApiImplicitParam("参数说明") 给接口参数添加说明,用于对单个参数进行说明
@ApiResponses; @ApiResponse 方法返回值的说明,@ApiResponses对多个返回值说明

4.1.1、接口类的使用

@Api:放在 请求的类上,与 @Controller 并列,说明类的作用,如用户模块,订单类等。

@Api的属性

属性名称 说明
value controller若指定了RequestMapping 访问地址,把路径赋值给value
tags 添加标签
description 描述
basePath 基本路径,基本上很少用
position swagger-ui中的显示顺序
produces 指明生成json、xml等格式,值为“application/json”
consumes 使用json或者xml,同上
protocols 协议类型,如: http, https, ws, wss.
authorizations 高级特性认证时配置
hidden 配置为true ,将在文档中隐藏

示例:

@Api(value="/test", tags="测试接口")
@Controller
@RequestMapping("/test")
public class TestController{}

4.1.2、接口方法使用的注解说明

@ApiOperation:"用在请求的方法上,说明方法的作用"

@ApiImplicitParams:用在请求的方法上,包含一组参数说明
@ApiImplicitParam:对单个参数的说明
name:参数名
value:参数的说明、描述
required:参数是否必须必填
paramType:参数放在哪个地方
· query --> 请求参数的获取:@RequestParam
· header --> 请求参数的获取:@RequestHeader
· path(用于restful接口)--> 请求参数的获取:@PathVariable
· body(请求体)--> @RequestBody User user
· form(普通表单提交)
dataType:参数类型,默认String,其它值dataType="int"
defaultValue:参数的默认值

@ApiResponses:方法返回对象的说明
@ApiResponse:每个参数的说明
code:数字,例如400
message:信息,例如"请求参数没填好"
response:抛出异常的类

示例:

@ApiOperation(value="登录",notes="这是一个登录接口的说明")
@ApiImplicitParams({
    @ApiImplicitParam(name="name",value="姓名",required=true,paramType="form",dataType="String"),
    @ApiImplicitParam(name="age",value="年龄",required=true,paramType="form",dataType="int")
})
@ApiResponses({
    @ApiResponse(code = 200, message = "请求成功"),
    @ApiResponse(code = 400, message = "请求参数没填好"),
    @ApiResponse(code = 404, message = "请求路径没有或页面跳转路径不存在")
}) 
@ResponseBody
@PostMapping("/login")
public JsonResult login(@RequestParam String name, @RequestParam Integer age){
    //...
    return JsonResult.ok(map);
}

4.2、实体类的注解

注解名称 说明
@ApiModel("POJO说明") 给模型类JAVABEAN等添加说明
@ApiModelProperty("POJO模型类属性说明") 给类属性添加说明

@ApiModel的用途有2个:
当请求数据描述,即 @RequestBody 时, 用于封装请求(包括数据的各种校验)数据;
当响应值是对象时,即 @ResponseBody 时,用于返回值对象的描述

@ApiModel的属性:

注解名称 默认值 说明
value 类名 提供中文说明
description "" 描述
parent Void.class 为模型提供父类,用来描述继承关系
discriminatory "" 支持模型继承和多态,使用鉴别器的字段的名称,可以断言需要使用哪个子类型
subTypes [{},...] 继承此类的子类数组
reference "" 指定对应类型定义的引用,覆盖指定的任何其他元数据

@ApiModelProperty的属性说明:

注解名称 默认值 说明
value "" 属性简要说明
name "" 运行覆盖属性的名称。重写属性名称
allowableValues "" 限制参数可接收的值,固定取值,固定范围
access "" 过滤属性,参阅:io.swagger.core.filter.SwaggerSpecFilter
notes "" 备注
dataType "" 参数的数据类型,可以是类名或原始数据类型,此值将覆盖从类属性读取的数据类型
required false 是否为必传参数,false:非必传参数; true:必传参数
position 0 允许在模型中显示排序属性
hidden false 隐藏模型属性,false:不隐藏; true:隐藏
example "" 属性的示例值
readOnly false 指定模型属性为只读,false:非只读; true:只读
reference "" 指定对应类型定义的引用,覆盖指定的任何其他元数据
allowEmptyValue false 允许传空值,false:不允许传空值; true:允许传空值

示例:

@ApiModel("用户")
Public class User{
    
    @ApiModelProperty("年龄")
    public Integer age;
    
    @ApiModelProperty(value="姓名", required=true)
    public String name;
}
上一篇 下一篇

猜你喜欢

热点阅读