前言在开始使用 Swagger 之前,我们先来了解下几个概念。名词释义SwaggerSwagger 是一个 RESTful 接口规范,现在流行的版本有 2.0 和 3.0 。OpenAPIOpenAPI 规范就是之前的 Swagger 规范,只是换了个名字。swagger.json/swagger.yamlswagger.json 或 swagger.yaml 是符合 Swagger 规范的接口描述文件。文件名称随意,这里只是举例。SpringfoxSpringfox 套件可以为 Spring 系列项目自动生成 swagger.json,还可以集成 Swagger UI。Swagger UISwagger UI 通过解析 swagger.[json/yaml],来生成在线接口文档。ReDocReDoc 是另一个 Swagger UI 工具。SpringfoxSpringfox 当前有两个主要版本:正式版 2.9.2 和 快照版 3.0.0-SNAPSHOT。建议读者先试用正式版。Maven 依赖(2.9.2)<properties> <springfox.version>2.9.2</springfox.version></properties><dependencies> <!– 生成 Swagger 文档 –> <dependency> <groupId>io.springfox</groupId> <artifactId>springfox-swagger2</artifactId> <version>${springfox.version}</version> </dependency> <!– 添加 Springfox Swagger UI 支持 –> <dependency> <groupId>io.springfox</groupId> <artifactId>springfox-swagger-ui</artifactId> <version>${springfox.version}</version> </dependency></dependencies>Maven 依赖(3.0.0-SNAPSHOT)编写 Swagger 配置类在 SpringBoot 启动类同级目录下添加该配置类。配置类 SwaggerConfig 上添加 @Configuration 注解,是为了让 Spring 识别到这是一个配置类。package org.qadoc.wiremock.web;import com.google.common.base.Predicates;import org.springframework.context.annotation.Bean;import org.springframework.context.annotation.Configuration;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 java.util.ArrayList;/** * Swagger 配置类 <br> * 创建时间:2019/4/10 15:35<br> * @author 李云 /@Configurationpublic class SwaggerConfig { @Bean public Docket mocklabAPI(){ return new Docket(DocumentationType.SWAGGER_2) .select() .apis(RequestHandlerSelectors.any()) //.apis(not(withClassAnnotation(CustomIgnore.class))) .paths(Predicates.not(PathSelectors.regex("/error."))) //不展示 Spring 自带的 error Controller .build() //.pathMapping("/") //.directModelSubstitute(LocalDate.class,String.class) //.genericModelSubstitutes(ResponseEntity.class) .useDefaultResponseMessages(false) //.tags(new Tag(“tagName”,“description”)) .apiInfo(apiInfo()) ; } private ApiInfo apiInfo(){ Contact contact = new Contact("","",""); return new ApiInfo( “MockLab API 文档”, “MockLab API 文档(Web端)”, “1.0.0”, “”, contact, “”, “”, new ArrayList<>() ); }}启用 Swagger在 SpringBoot 的启动类上添加 @EnableSwagger2 注解。package org.qadoc.wiremock.web;import org.springframework.boot.SpringApplication;import org.springframework.boot.autoconfigure.SpringBootApplication;import springfox.documentation.swagger2.annotations.EnableSwagger2;@SpringBootApplication@EnableSwagger2public class MockLabWebApplication { public static void main(String[] args) { SpringApplication.run(MockLabWebApplication.class, args); }}Swagger 文档注解Swagger 的文档注解有三类:resource(Controller 类) 注解operation(API 方法)注解API models(实体类)注解注解概览注解描述@Api标记一个类为 Swagger 资源。@ApiImplicitParam表示 API Operation 中的单个参数。@ApiImplicitParams包装注解,包含多个 @ApiImplicitParam 注解@ApiModel提供 Swagger models 的附加信息@ApiModelProperty添加和操作 model 属性的数据。@ApiOperation描述一个特定路径的 operation(通常是 HTTP 方法)@ApiParam为 operation 参数添加额外的 meta-data。@ApiResponse描述 operation 可能的响应。@ApiResponses包装注解,包含多个 @ApiResponse 注解。@ResponseHeader表示响应头。Resource API 声明@Api声明该 API 接口类需要生成文档。@Api(tags = {“应用健康检查”})@RestController@RequestMapping(value = “/healthcheck”)public class HealthCheckController { …}属性列表属性描述tags属性用来对接口进行分组管理。当然你可以添加多个 tag,那么该类下的接口会在这两个分组里出现。注意事项:如果没有指定响应的 Content-Type ,springfox 的默认值是 /。有两种指定方式。在 Controller 类或方法上的 @RequestMapping 注解中增加 produces 属性值。@RequestMapping(value = “/healthcheck”,produces = MediaType.APPLICATION_JSON_VALUE)在 Swagger 配置类中指定默认值。docket… .produces(Sets.newHashSet(MediaType.APPLICATION_JSON_VALUE)) .consumes(Sets.newHashSet(MediaType.APPLICATION_JSON_VALUE))…@ApiIgnore声明该 API 接口类不需要生成文档。@ApiIgnore(“过时的API”)@ConditionalOnExpression(“false”)@RestController@RequestMapping(value = “/record/xianbank”)public class RecordXianBankController { …}Operation 声明@ApiOperation用于接口方法上,描述该接口相关信息。@ApiOperation( nickname = “healthCheckUsingGet”, value = “应用健康检查”, notes = “用于检查应用是否可以正常访问。”, produces = MediaType.APPLICATION_JSON_VALUE, response = HealthCheckRes.class)@GetMapping()public BaseResult<HealthCheckRes.AppStatus> healthCheck() { …}属性列表属性描述nicknameoperationID,接口唯一标识value接口名称notes接口描述信息produces响应 Content-Type,示例:“application/json, application/xml"consumes请求 Content-Type,示例:“application/json, application/xml"responseresponse body Model,响应体结构及单个字段示例参考资料:@ApiModelProperty throwing NumberFormatException if example value is not set