Springboot整合swagger

528 阅读1分钟

添加依赖

<!--Swagger-UI API文档生产工具-->
<dependency>
  <groupId>io.springfox</groupId>
  <artifactId>springfox-swagger2</artifactId>
  <version>2.7.0</version>
</dependency>
<dependency>
  <groupId>io.springfox</groupId>
  <artifactId>springfox-swagger-ui</artifactId>
  <version>2.7.0</version>
</dependency>

添加Swagger-UI的配置

注:不同版本,配置会有所不同

**给Controller添加Swagger注解
**

常用注解:
@Api:用于修饰Controller类,生成Controller相关文档信息
@ApiOperation:用于修饰Controller类中的方法,生成接口方法相关文档信息
@ApiParam:用于修饰接口中的参数,生成接口参数相关文档信息
@ApiModelProperty:用于修饰实体类的属性,当实体类是请求参数或返回结果时,直接生成相关文档信息

注:

需要注意springboot和swagger的版本

SpringBoot处理映射匹配的默认策略发生变化
请求路径与 Spring MVC 处理映射匹配的默认策略已从AntPathMatcher更改为PathPatternParser。
你可以设置spring.mvc.pathmatch.matching-strategy为ant-path-matcher来改变它。

springboot 2.6.0之前
public static class Pathmatch {
	private MatchingStrategy matchingStrategy = MatchingStrategy.ANT_PATH_MATCHER;
}
springboot2.6.0之后
public static class Pathmatch {
    private MatchingStrategy matchingStrategy = MatchingStrategy.PATH_PATTERN_PARSER;
}
如果升级springboot到2.6之后,需要设置spring.mvc.pathmatch.matching-strategy=ant-path-matcher来兼容Swagger2


swagger版本
1、Swagger 2.x 版本
springboot 2.5.6 ✚ swagger 2.6.1~2.9.2配置属下
只需要在启动类上加 @EnableSwagger2 注解即可
访问地址:http://127.0.0.1:8080/swagger-ui.html

2、Swagger 3.x 版本
springboot 2.5.6 ✚ swagger 3.0.0配置属下
只需要在启动类上加 @EnableSwagger2注解即可访问地址:http://127.0.0.1:8080/swagger-ui/index.html

springboot 2.6.5 ✚ swagger 3.0.0配置属下
application.yml 或applicaiton.properties 中添 必须 加如下配置
spring:
  mvc:
    pathmatch:
      matching-strategy: ant_path_matcher
只需要在启动类上加 @EnableSwagger2 注解即可访问地址:http://127.0.0.1:8080/swagger-ui/index.html

Knife4j 版本

访问地址:http://127.0.0.1:8080/doc.html,访问方式和之前的保持一致,如果项目中配置拦截器等,需要放开doc.html静态资源

参考文献

swagger
https://blog.csdn.net/qq_33334411/article/details/125655201