定义
Swagger 是一个规范和完整的框架,用于生成、描述、调用和可视化 RESTful 风格的 Web 服务。
作用
使客户端和文件系统作为服务器以同样的速度来更新,API文档和API同步更新。文件的方法、参数和模型紧密集成到服务器端的代码,允许 API 来始终保持同步。Swagger 可以很方便地部署管理和使用功能强大的 API 。
可以直接运行,还可以在线测试API接口。
官网
导入依赖
<!--集成swagger-->
<!-- https://mvnrepository.com/artifact/io.springfox/springfox-boot-starter -->
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-boot-starter</artifactId>
<version>3.0.0</version>
</dependency>
<!-- https://mvnrepository.com/artifact/io.springfox/springfox-swagger-ui -->
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger-ui</artifactId>
<version>3.0.0</version>
</dependency>
上面的可能存在于SpringBoot版本不匹配问题,出现问题可尝试:
package com.example.project.config;
import org.springframework.context.annotation.Configuration;
import springfox.documentation.swagger2.annotations.EnableSwagger2;
@Configuration
@EnableSwagger2 //开启swagger
public class SwaggerConfig {
}
config开启swagger服务
<!--集成swagger-->
<!-- https://mvnrepository.com/artifact/io.springfox/springfox-boot-starter -->
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-boot-starter</artifactId>
<version>3.0.0</version>
</dependency>
<!-- https://mvnrepository.com/artifact/io.springfox/springfox-swagger-ui -->
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger-ui</artifactId>
<version>3.0.0</version>
</dependency>
注意事项
如果项目中同时存在Spring Boot和Swagger 3.0.0 可能会出错。
报错原因
Springboot2.6以后将SpringMVC 默认路径匹配策略从AntPathMatcher 更改为PathPatternParser
Springfox 使用的路径匹配是基于AntPathMatcher的,而Spring Boot 2.6.X使用的是PathPatternMatcher
解决方案
application.properties中添加:
spring.mvc.pathmatch.matching-strategy=ANT_PATH_MATCHER
或者在yaml中添加:
spring:
mvc:
pathmatch:
matching-strategy: ant_path_matcher
测试运行
http://localhost:8080/swagger-ui.html