Swagger
介绍
- Swagger是一款REST APIs文档生成工具。
- Swagger官方定义:Swagger是一款开源工具,依据OpenAPI规范(OpenAPI Specification,简称OAS)可以帮助你设计,构建,生成文档,消费(调用)REST APIs。主要的工具包含:
- Swagger Editor:基于web的一个工具,用于编写符合OpenAPI规范的模型
- Swagger UI:用于展示REST APIs文档,并提供一些交互操作
- Swagger Codegen: 依据OpenAPI规范来生成服务端和客户端代码
优点
- 通过代码和注释自动生成文档。在Swagger框架下,开发人员可对服务进行归类说明,对方法,模型,返回结果等进行详细说明。方便开发人员在编写代码的同时,编写文档信息。自动生成,只需很少的编辑工作,就能获得完整的REST APIs文档
- 提供了UI界面。既展示接口信息,又提供了参数校验,测试功能
- 形成了文档规范,支持不同的语言
- 提供丰富的组件。
SpringBoot+Swagger集成
使用官方依赖
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger2</artifactId>
<version>2.9.2</version>
</dependency>
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger-ui</artifactId>
<version>2.9.2</version>
</dependency>
<dependency>
<groupId>org.codehaus.jackson</groupId>
<artifactId>jackson-core-asl</artifactId>
<version>1.9.13</version>
</dependency>```
配置Swagger
- 要使用Swagger,我们必须对Swagger进行配置,我们需要创建一个Swagger的配置类,比如可以命名为
SwaggerConfig.java
package com.dduan.common;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
import springfox.documentation.builders.ApiInfoBuilder;
import springfox.documentation.builders.PathSelectors;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.service.ApiInfo;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2;
@Configuration
@EnableSwagger2
public class SwaggerConfig implements WebMvcConfigurer {
@Bean
public Docket createRestApi() {
return new Docket(DocumentationType.SWAGGER_2)
.apiInfo(apiInfo())
.select()
.apis(RequestHandlerSelectors.basePackage("com.dduan.controller"))
.paths(PathSelectors.regex(".sys/login"))
.build();
}
private ApiInfo apiInfo() {
return new ApiInfoBuilder()
.title("XX项目API")
.description("XX项目SwaggerAPI管理")
.termsOfServiceUrl("")
.version("1.0")
.build();
}
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry
.addResourceHandler("swagger-ui.html")
.addResourceLocations("classpath:/META-INF/resources/");
registry
.addResourceHandler("/webjars/**")
.addResourceLocations("classpath:/META-INF/resources/webjars/");
}
}
场景
@Api(tags = "用户管理")
@RestController
@RequestMapping("/sys")
public class UserController {
}
@Api(tags = "用户管理")
@RestController
@RequestMapping("/sys")
public class UserController {
@ApiOperation(value = "用户登录")
@RequestMapping(value = "/login", method = RequestMethod.POST, consumes = MediaType.APPLICATION_JSON_VALUE)
public Resp login(@RequestBody LoginVo loginVo) {
}
}
接口文档展示
- 访问地址:
localhost:端口号/swagger-ui.html
- API doc 页面及功能介绍
- 点击 Try it out 按钮页面