Swagger在线文档

摩森特沃 2021年07月06日 764次浏览

声明:本文多处直接引用了文末的参考链接中的内容,如有侵权,请联系删除

项目集成Swagger2

Swagger2的实现原理

实现原理

  • 项目启动,Spring初始化上下文,加载Swagger相关的Bean,并由此扫描系统中需要生成的API文档注解获取注释信息

Spring boot集成Swagger2

  1. 引入maven依赖
<!-- Swagger2基础依赖 -->
<dependency>
    <groupId>io.springfox</groupId>
    <artifactId>springfox-swagger2</artifactId>
    <version>3.0.0</version>
</dependency>
<dependency>
    <groupId>io.springfox</groupId>
    <artifactId>springfox-swagger-ui</artifactId>
    <version>3.0.0</version>
</dependency>
<!-- Swagger2基础依赖结束 -->

<!-- Swagger2皮肤依赖,如果只需要使用原生的Swagger文档,则不需要引入 -->
<dependency>
    <groupId>com.github.xiaoymin</groupId>
    <artifactId>knife4j-spring-boot-starter</artifactId>
    <version>3.0.3</version>
    <exclusions>
        <exclusion>
             <artifactId>swagger-models</artifactId>
             <groupId>io.swagger</groupId>
        </exclusion>
        <exclusion>
             <artifactId>swagger-annotations</artifactId>
             <groupId>io.swagger</groupId>
        </exclusion>
    </exclusions>
</dependency>
<!-- Swagger2皮肤依赖结束 -->
  1. 编写Swagger配置文件
package com.mostall.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import springfox.documentation.builders.ApiInfoBuilder;
import springfox.documentation.builders.PathSelectors;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.service.ApiInfo;
import springfox.documentation.service.Contact;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2;

/**
 * @author sut
 * @version v1.0
 * @since 2021/8/28
 */
@Configuration
@EnableSwagger2
public class Swagger2Config {

    // 配置swagger2核心
    @Bean
    public Docket creatRestApi() {
        return new Docket(DocumentationType.SWAGGER_2) // 指定api类型为swagger2
                // api基本信息
                .apiInfo(apiInfo()) // 用于定义api文档汇总信息
                // 设置允许保暴露的接口
                .select()
                .apis(RequestHandlerSelectors.basePackage("com.mostall.controller")) // 指定controller包
                .paths(PathSelectors.any()) // 所有controller
                .build();
    }

    private ApiInfo apiInfo() {
        return new ApiInfoBuilder()
                .title("api文档") // 文档标题
                .description("api文档")
                .contact(new Contact("mostall", "https://www.mostall.com", "seta2012@foxmail.com"))
                .version("1.0.0")
                .build();
    }
}
  1. 编写静态资源拦截配置
package com.mostall.config;

import com.google.common.collect.Lists;
import com.mostall.interceptor.UserTokenInterceptor;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

import java.util.List;

/**
 * web相关配置,包括资源放行,redis的相关配置信息
 *
 * @author sut
 * @version v1.0
 * @since 2021/8/28
 */
@Configuration
public class WebConfig implements WebMvcConfigurer {

    /**
     * 静态资源配置
     */
    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        // 配置本地文件夹目录映射
        // registry.addResourceHandler("/**")
        // 项目中的文件目录,此处也可以直接使用项目以外的文件目录
        //         .addResourceLocations("file:uploads/");

        // 配置其他静态资源
        registry.addResourceHandler("/**")
                .addResourceLocations("file:uploads/")
                .addResourceLocations("classpath:/static/");

        // 配置knife4j 皮肤静态资源
        registry.addResourceHandler("doc.html")
                .addResourceLocations("classpath:/META-INF/resources/");

        // 对swagger2 ui库中的静态文件进行映射
        registry.addResourceHandler("/swagger-ui/**")
                .addResourceLocations("classpath:/META-INF/resources/webjars/springfox-swagger-ui/");
        registry.addResourceHandler("/webjars/**")
                .addResourceLocations("classpath:/META-INF/resources/webjars/");
    }
}
  1. 在controller或者vo类上使用swagger相关注解

Swagger2常用注解说明

Api

Api 用在类上,说明该类的作用。可以标记一个Controller类做为swagger 文档资源,使用方式:

@Api(tags={"用户接口"})

与Controller注解并列使用。 属性配置:

属性名称属性类型备注默认值
valueStringurl的路径值“”
tagsString[]如果设置这个值、value的值会被覆盖。可以配置多个,当配置多个的时候,在页面中会显示多个接口的信息“”
producesStringMIME类型列表(output),如: "application/json, application/xml"“”
consumesStringMIME类型列表(input),如: "application/json, application/xml"“”
protocolsString协议类型,如: http、https、ws、wss“”
authorizationsAuthorization[]获取授权列表(安全声明),如果未设置,则返回一个空的授权值
hiddenboolean是否在文档中隐藏false

在SpringMvc中的配置如下:

@Controller
@RequestMapping(value = "/api/pet", produces = {APPLICATION_JSON_VALUE, APPLICATION_XML_VALUE})
@Api(value = "/pet", description = "Operations about pets")
public class PetController {

}

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"})

与Controller中的方法并列使用。属性配置:

属性名称属性类型备注默认值
valueStringurl的路径值
notesString对api资源的描述""
tagsString[]标签""
responseClass<?>响应类型(即返回对象)Void.class
responseContainerString声明包装的响应容器(返回对象类型)。有效值为 "List", "Set" or "Map"“”
responseReferenceString指定对响应类型的引用。将覆盖任何指定的response()类“”
httpMethodString指定HTTP方法,"GET"、"HEAD"、"POST"、"PUT"、"DELETE"、"OPTIONS"、"PATCH"“”
nicknameString第三方工具唯一标识,默认为空“”
producesStringMIME类型列表(output),如: "application/json, application/xml"“”
consumesStringMIME类型列表(input),如: "application/json, application/xml"“”
protocolsString协议类型,如: http、https、ws、wss“”
authorizationsAuthorization[]获取授权列表(安全声明),如果未设置,则返回一个空的授权值
hiddenboolean是否在文档中隐藏false
responseHeadersResponseHeader[]响应头列表
codeint响应的HTTP状态代码200
extensionsExtension[]扩展属性列表数组
ignoreJsonViewboolean序列化时是否忽略false

在SpringMvc中的配置如下:

@RequestMapping(value = "/order/{orderId}", method = GET)
@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.class,
          tags = { "Pet Store" })
public ResponseEntity<Order> getOrderById(@PathVariable("orderId") String orderId)
      throws NotFoundException {
	Order order = storeData.get(Long.valueOf(orderId));
	if (null != order) {
		return ok(order);
	} else {
		throw new NotFoundException(404, "Order not found");
	}
}

ApiParam

ApiParam用在参数中,对请求的参数进行标记,使用方式:

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

与Controller中的方法并列使用。属性配置:

属性名称属性类型备注默认值
nameString属性名称""
valueString属性值""
defaultValueString默认属性值""
allowableValuesString可以不配置""
requiredboolean是否属性必填false
accessString不过多描述""
allowMultipleboolean是否可以接受多个值false
hiddenboolean是否在文档中隐藏false
exampleString单个示例""
examplesExample参数示例
typeString ""
formatString ""
allowEmptyValueboolean是否允许空值false
readOnlyboolean是否只读false
collectionFormatString ""

在SpringMvc中的配置如下:

public ResponseEntity<Order> getOrderById(
      @ApiParam(value = "ID of pet that needs to be fetched", allowableValues = "range[1,5]", required = true)
      @PathVariable("orderId") String orderId)

ApiModel

ApiModel用在实体类上,用于对实体类参数进行说明。使用方式代码如下所示。

@ApiModel(value = "AddUserParam", description = "新增用户参数")
public class AddUserParam {
}

ApiModel通常与ApiModelProperty配合使用。属性配置:

属性名称属性类型备注默认值
valueString参数名称""
descriptionString参数描述""
parentClass<?>父类型Void.class
discriminatorString ""
subTypesClass<?>[]子类型{}
referenceString指定对相应类型定义的引用,覆盖指定的任何参数值""

ApiModelProperty

ApiModelProperty() 用于字段,表示对 model 属性的说明。使用方式代码如下所示。

@Data@ApiModel(value = "com.biancheng.auth.param.AddUserParam", description = "新增用户参数")
public class AddUserParam {    
    @ApiModelProperty(value = "ID")    
    private String id;    
    
    @ApiModelProperty(value = "名称")
    private String name;    
    
    @ApiModelProperty(value = "年龄")
    private int age;
}

效果如图 2 右下角。

ApiModelProperty通常用在ApiModel标记的类的属性上。属性配置:

属性名称属性类型备注默认值
nameString属性名称""
valueString属性值""
allowableValuesString可以不配置""
accessString允许从API文档中过滤参数""
notesString注释说明""
dataTypeString参数类型,默认String,其它值dataType="Integer"""
requiredboolean默认为falsefalse
positionint显示的顺序位置0
hiddenboolean是否在文档中隐藏false
exampleString单个示例""
accessModeAccessMode AccessMode.AUTO
referenceString指定对相应类型定义的引用,覆盖指定的任何参数值""
allowEmptyValueboolean是否允许空值false

ApiResponse

ApiResponse:响应配置,一般用于表达一个错误的响应信息,使用方式:

@ApiResponse(code = 400, message = "Invalid user supplied")

与Controller中的方法并列使用。 属性配置:

属性名称属性类型备注默认值
codeinthttp的状态码
messageString状态码对应的响应信息""
responseClass<?>默认响应类 VoidVoid.class
referenceString指定对相应类型定义的引用,覆盖指定的任何参数值""
responseHeadersResponseHeader[]响应头列表
responseContainerString声明包装的响应容器(返回对象类型)。有效值为 "List", "Set" or "Map"""
examplesExample参数示例

在SpringMvc中的配置如下:

@RequestMapping(value = "/order", method = POST)
@ApiOperation(value = "Place an order for a pet", response = Order.class)
@ApiResponses({ @ApiResponse(code = 400, message = "Invalid Order") })
public ResponseEntity<String> placeOrder(
	@ApiParam(value = "order placed for purchasing the pet", required = true) Order order) {
	storeData.add(order);
	return ok("");
}

ApiResponses

ApiResponses用于表示一组配置,使用方式:

 @ApiResponses({ @ApiResponse(code = 400, message = "Invalid Order") })

与Controller中的方法并列使用。 属性配置:

属性名称属性类型备注默认值
valueApiResponse[]多个ApiResponse配置

在SpringMvc中的配置如下:

@RequestMapping(value = "/order", method = POST)
@ApiOperation(value = "Place an order for a pet", response = Order.class)
@ApiResponses({ @ApiResponse(code = 400, message = "Invalid Order") })
public ResponseEntity<String> placeOrder(
	@ApiParam(value = "order placed for purchasing the pet", required = true) Order order) {
	storeData.add(order);
	return ok("");
}

ResponseHeader

ResponseHeader用于响应头配置,使用方法

@ResponseHeader(name="head1",description="response head conf")

与Controller中的方法并列使用。 属性配置:

属性名称属性类型备注默认值
nameString响应头名称""
descriptionString头描述""
responseClass<?>响应类型(即返回对象)Void.class
responseContainerString声明包装的响应容器(返回对象类型)。有效值为 "List", "Set" or "Map"""

在SpringMvc中的配置如下:

@ApiModel(description = "群组")

其他

ApiImplicitParam 和 ApiImplicitParams

ApiImplicitParam 和 ApiImplicitParams用于方法上,为单独的请求参数进行说明。使用方式:

@ApiImplicitParams({ @ApiImplicitParam(name = "id", value = "用户ID", dataType = "string", paramType = "query", required = true, defaultValue = "1") })
@ApiResponses({ @ApiResponse(code = 200, message = "OK", response = UserDto.class) })
@GetMapping("/user")
public UserDto getUser(@RequestParam("id") String id) {    
    return new UserDto();
}

ApiImplicitParam属性配置:

属性名称属性类型备注默认值
nameString参数名,参数名称可以覆盖方法参数名称,路径参数必须与方法参数一致""
valueString参数中文说明""
defaultValueString参数的默认值""
allowableValuesString限制参数的可接受值。1、以逗号分隔的列表;2、范围值;3、设置最小值/最大值""
requiredboolean参数是否必须传false
accessString允许从API文档中过滤属性“”
allowMultipleboolean是否可以接受多个值false
dataTypeString参数类型,默认String,其它值dataType="Integer"“”
dataTypeClassClass<?>参数数据类型Void.class
paramTypeString参数放在哪个地方,取值为header、query、path、body、form""
exampleString单个示例“”
examplesExample参数示例
typeString “”
formatString ""
allowEmptyValueboolean是否允许空值false
readOnlyboolean是否只读false
collectionFormatString ""

ApiImplicitParams属性配置:

属性名称属性类型备注默认值
valueApiImplicitParam[]多个ApiImplicitParam配置

引用参考