目录
Swagger 3.0
1. Introduction
“API Development for Everyone”
Swagger是一个更好的书写API文档的框架,用于前后端分离时代的联系。
在前后端分离时代,前端负责渲染页面,后端负责功能实现、数据访问、服务等,后端通过提供给前端的API进行交互,前后端相对独立,低耦合。但是这种开发模式可能会产生一些问题,比如前后端独立开发,前端想要增加一个展示可能需要后端增加许多代码,在沟通上产生问题。这时候Swagger为了简化以往的自己手写并更新API文档而诞生了。Swagger是RESTful API文档自动生成框架,可以直接运行,并且支持在线测试API。
Swagger 3.0 相比于 2.x 在配置上有一定区别。主要体现在依赖变为springfox-boot-starter
,启动注解由@EnableSwagger2
变为@EnableOpenApi
注解,访问路径/swagger-ui.html
变为/swagger-ui/index.html
等。
2. SpringBoot集成Swagger 3.0
步骤:
-
导入Maven依赖
<dependency> <groupId>io.springfox</groupId> <artifactId>springfox-boot-starter</artifactId> <version>3.0.0</version> </dependency>
-
自定义配置类,并在配置类上加
@EnableOpenApi
注解import org.springframework.context.annotation.Configuration; import springfox.documentation.oas.annotations.EnableOpenApi; @Configuration @EnableOpenApi public class SwaggerConfig { }
-
在Controller类上添加Swagger注解
import io.swagger.annotations.Api; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RestController; @RestController @Api(tags="Hello,Swagger3.0") public class HelloController { @GetMapping("/hello") public String hello(){ return "hello123"; } }
-
启动应用,访问
/swagger-ui/index.html
3. Swagger Configuration
3.1 DocumentationType
Swagger配置的核心实例为Docket
对象
在Docket对象中我们找到了构造方法:
public Docket(DocumentationType documentationType) {
this.apiInfo = ApiInfo.DEFAULT;
this.groupName = "default";
this.enabled = true;
this.genericsNamingStrategy = new DefaultGenericTypeNamingStrategy();
this.applyDefaultResponseMessages = true;
this.host = "";
this.pathMapping = Optional.empty();
this.apiSelector = ApiSelector.DEFAULT;
this.enableUrlTemplating = false;
this.vendorExtensions = new ArrayList();
this.globalRequestParameters = new ArrayList();
this.documentationType = documentationType;
}
首先我们来探究一下这个方法中传递的参数DocumentationType:
public class DocumentationType extends SimplePluginMetadata {
public static final DocumentationType SWAGGER_12 = new DocumentationType("swagger", "1.2");
public static final DocumentationType SWAGGER_2 = new DocumentationType("swagger", "2.0");
public static final DocumentationType OAS_30 = new DocumentationType("openApi", "3.0");
...
}
里面已经定义类三个静态常量供我们使用,由于我们使用的是Swagger3.0,所以使用OAS_30这个参数,即传递DocumentationType.OAS_30即可。
3.2 ApiInfo
接下来我们关注的是ApiInfo:
public class ApiInfo {
public static final Contact DEFAULT_CONTACT = new Contact("", "", "");
public static final ApiInfo DEFAULT;
private final String version;
private final String title;
private final String description;
private final String termsOfServiceUrl;
private final String license;
private final String licenseUrl;
private final Contact contact;
private final List<VendorExtension> vendorExtensions;
...
public ApiInfo(String title, String description, String version, String termsOfServiceUrl, Contact contact, String license, String licenseUrl, Collection<