为什么要使用swagger
- 首先我们要先了解swagger是个什么东西:
Swagger 是一个流行的 API 文档工具,它提供了许多好处,使得它成为开发人员和团队在开发和维护 API 时的首选工具之一,其他竞品包括:Apiary、ApiDoc、Redoc等
- API 文档自动生成:Swagger 可以根据您的代码自动生成 API 文档,这意味着您不必手动编写和更新文档,从而节省了大量时间和精力。
- 统一的文档格式:Swagger 使用 OpenAPI 规范来描述 API,这使得生成的文档具有统一的格式和结构,易于阅读和理解。这样做有助于团队成员更容易地理解 API 的使用方式和细节。
- 交互式文档:Swagger 生成的文档是交互式的,意味着您可以直接在文档中尝试 API,包括发送请求并查看响应。这种实时交互性有助于开发人员更快地理解和测试 API。
- 统一的开发体验:使用 Swagger 让开发团队和 API 使用者有了统一的接口定义,这样可以减少沟通成本,并确保开发人员对 API 的使用方式达成一致。
- swagger官网:https://swagger.io/# 【最好的方法果然还是得看官网手册】
- 而 Swagger + Knife4j
上手
- 添加依赖
<!--knife4j-->
<dependency>
<groupId>com.github.xiaoymin</groupId>
<artifactId>knife4j-spring-boot-starter</artifactId>
<version>3.0.3</version>
</dependency>
- 配置yml文件【如果 springboot version >= 2.6,需要添加如下配置:】
spring:
mvc:
pathmatch:
matching-strategy: ANT_PATH_MATCHER
- 编写配置文件
import lombok.extern.slf4j.Slf4j;
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.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2WebMvc;
/**
* @auther : LuYouxiao
* @date
* @Description
*/
@Configuration
@EnableSwagger2WebMvc
@Slf4j
@Profile("dev")//限制swagger只能在dev环境下生效
public class SwaggerConfiguration {
/**
* 通过knife4j生成接口文档
* @return
*/
@Bean
public Docket serverDocket() {
ApiInfo apiInfo = new ApiInfoBuilder()
.title("接口文档标题")
.version("1.0")
.description("接口文档描述")
.build();
Docket docket = new Docket(DocumentationType.SWAGGER_2)
.apiInfo(apiInfo)
.select()
.apis(RequestHandlerSelectors.basePackage("com.luyouxiao.controller"))
.paths(PathSelectors.any())
.build();
return docket;
}
}
- 添加接口文档
@Slf4j
@Api("套餐接口")
@RestController
@RequestMapping("/setmeal")
public class ComboController {
/**
* 新增套餐
*
* @param setmealDTO
* @return
*/
@PostMapping
@ApiOperation("新增套餐")
public Result save(@RequestBody SetmealDTO setmealDTO) {
······
return Result.success();
}
}
这样一个基本的swagger+knife4j接口文档就大功告成了