SpringBoot教程(十七) | SpringBoot集成swagger
- 一、Swagger的简述
- 二、SpringBoot集成swagger2
- 1. 引入依赖
- 2. 新建SwaggerConfig配置类
- 当 SpringBoot为2.6.x及以上时 需要注意
 
- 3.配置Swagger开关
- 4. 给Controller 添加注解(正式使用)
- 5. SpringSecurity中配置 (看需求使用)
 
- 三、SpringBoot集成swagger3
一、Swagger的简述
Swagger(现在更广泛地被称为OpenAPI)是一套基于OpenAPI规范构建的开源工具,它主要用于生成、描述、调用和可视化RESTful风格的Web服务。
 其中最重要的表现在于实时接口文档,可以更好的让前端进行联调
二、SpringBoot集成swagger2
1. 引入依赖
首先,你需要在项目的
pom.xml文件中添加Swagger2的依赖。
<dependencies>  <!-- Swagger2 -->  <dependency>  <groupId>io.springfox</groupId>  <artifactId>springfox-swagger2</artifactId>  <!-- 注意:这里使用的是2.9.2版本 用的人比较多 -->  <version>2.9.2</version> </dependency>  <dependency>  <groupId>io.springfox</groupId>  <artifactId>springfox-swagger-ui</artifactId>  <!-- 与swagger2版本保持一致 -->  <version>2.9.2</version> </dependency>  
</dependencies>
2. 新建SwaggerConfig配置类
@EnableSwagger2
@Configuration  
@EnableSwagger2  
public class SwaggerConfig {  @Bean  public Docket docket() {  return new Docket(DocumentationType.SWAGGER_2)  .select()  //通过包路径来指定哪些Controller中的API需要被Swagger扫描并生成文档。//这里指定了"com.yourcompany.yourproject.controller"包及其子包中的所有Controller。.apis(RequestHandlerSelectors.basePackage("com.yourcompany.yourproject.controller"))  //扫描所有路径  .paths(PathSelectors.any()) .build()  //设置API的元数据信息,如标题、描述、版本等。//这些信息会显示在Swagger UI的顶部。   .apiInfo(apiInfo());}  private ApiInfo apiInfo() {  return new ApiInfoBuilder()  .title("你的项目名称")  .description("项目的API描述")  .version("1.0")  .build();  }  
}
如果你只想包含特定路径的API,可以使用其他PathSelectors方法,
 如antPath(“/user/**”)来匹配所有以"/user/"开头的路径。
可以把 .paths(PathSelectors.any())  换成 .paths(PathSelectors.antPath("/user/**"))
当 SpringBoot为2.6.x及以上时 需要注意
由于SpringBoot 2.6.x及以上版本使用了新的路径匹配策略(PathPatternMatcher),
而Swagger(尤其是Springfox-swagger2)通常使用的是AntPathMatcher,
这可能会导致两者之间的不兼容问题。
在application.properties或application.yml文件中,
 可以将SpringBoot的默认路径匹配策略更改为AntPathMatcher,以解决与Swagger的兼容性问题。
 配置示例如下:
properties写法如下
spring.mvc.pathmatch.matching-strategy=ant_path_matcher
或者在application.yml中:
spring:  mvc:  pathmatch:  matching-strategy: ant_path_matcher
3.配置Swagger开关
可以在application.properties或application.yml文件中定义不同的环境配置,
 然后在Swagger配置类中根据当前激活的Profile来决定是否启用Swagger。
application.yml示例:
spring:  profiles: #指定激活 active: dev  --- 
#测试环境 
spring:  config:  activate:  on-profile: dev  
swagger:  enabled: true  ---  
#开发环境
spring:  config:  activate:  on-profile: prod  
swagger:  enabled: false
@Configuration  
@EnableSwagger2  
public class SwaggerConfig {  // 使用@Value注解读取配置文件中的swagger.enabled值  @Value("${swagger.enabled:false}")  private Boolean swaggerShow;  @Bean  public Docket docket() {  return new Docket(DocumentationType.SWAGGER_2)  .enable(swaggerShow).select()  // 通过包路径来指定哪些Controller中的API需要被Swagger扫描并生成文档  .apis(RequestHandlerSelectors.basePackage("com.yourcompany.yourproject.controller"))  // 扫描所有路径  .paths(PathSelectors.any())  .build()  // 设置API的元数据信息  .apiInfo(apiInfo());   }  private ApiInfo apiInfo() {  return new ApiInfoBuilder()  .title("你的项目名称")  .description("项目的API描述")  .version("1.0")  .build();  }  
}
4. 给Controller 添加注解(正式使用)
import com.mcy.springbootswagger.User.User;
import com.mcy.springbootswagger.service.UserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;@RestController
@RequestMapping("/user")
//说明接口文件
@Api(value = "测试接口", tags = "用户管理相关的接口", description = "用户测试接口")
public class UserController {@Autowiredprivate UserService userService;/*** 保存数据* @param user* @return*/@PostMapping(value = "/save")//方法参数说明,name参数名;value参数说明,备注;dataType参数类型;required 是否必传;defaultValue 默认值@ApiImplicitParam(name = "user", value = "新增用户数据")//说明是什么方法(可以理解为方法注释)@ApiOperation(value = "添加用户", notes = "添加用户")public String saveUser(User user){userService.save(user);return "保存成功";}/*** 根据id查询用户* @param id* @return*/@GetMapping(value = "findById")@ApiOperation(value = "根据id获取用户信息", notes = "根据id查询用户信息")public User getUser(Integer id){return userService.findById(id);}@DeleteMapping(value = "deleteById")@ApiOperation(value = "根据id删除数据", notes = "删除用户")public String delete(Integer id){userService.deleteById(id);return "删除成功";}
}运行项目,输入http://localhost:8080/swagger-ui.html访问Swagger页面,页面如下:
由于我们只给用户接口添加了注解,所有用户接口是可以直接观察中文文档的。

 
- 点击需要测试的接口方法后,
 可以看到接口需要的参数,请求地址及接口说明信息。
 点击右上角的Try it out即可对接口进行测试。
  
  
- 查询结果:
  
 这里这些了部分接口进行测试,可以根据项目需求自行添加其他接口。
5. SpringSecurity中配置 (看需求使用)
如果Spring Boot项目中集成了Spring Security,接口会被拦截,需要在Spring Security的配置类中重写configure方法,对接口进行过滤一下。代码如下:
@Override
public void configure(WebSecurity web) throws Exception {web.ignoring().antMatchers("/swagger-ui.html").antMatchers("/v2/**").antMatchers("/swagger-resources/**");
}
三、SpringBoot集成swagger3
参考文章
 【1】SpringBoot之整合Swagger2(完整版)
 【2】SpringBoot整合Swagger2(完整版)
 【3】SpringBoot教程(十六) | SpringBoot集成swagger(全网最全)
 【4】springboot 2.7版本整合swagger2代码实现
 【5】【Swagger】maven项目整合Swagger(含Springfox3.0与spring boot 2.6.0及以上版本冲突解决办法)
 【6】一篇搞定SpringBoot任意版本集成Swagger各种版本