一、Swagger介绍
后端分离开发,后端需要编写接⼝说明⽂档,会耗费⽐较多的时间 swagger是⼀个⽤于⽣成服务器接⼝的规范性⽂档、并且能够对接口进⾏测试的⼯具
二、Swagger的作用
- ⽣成接口说明⽂档
- 对接口进行测试
三、Springboot整合Swagger的步骤
1.在api子工程添加依赖(Swagger2 \ Swagger UI)
<!-- https://mvnrepository.com/artifact/io.springfox/springfox-swagger2 -->
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger2</artifactId>
<version>2.9.2</version>
</dependency>
<!-- https://mvnrepository.com/artifact/io.springfox/springfox-swagger-ui -->
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger-ui</artifactId>
<version>2.9.2</version>
</dependency>
2.在api子工程程创建Swagger的配置(Java配置方式)
package com.dcc.mall.config;
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.service.Contact;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2;
/**
* @Author: 戴传春
* @Description: TODO
* @DateTime: 2025/3/18 11:59
**/@Configuration // 表明这个类可以用来做bean定义的来源。
@EnableSwagger2 // 启用Swagger2支持。
public class SwaggerConfig {
/*
* swagger会帮助我们生成接口文档
* 1:配置生成的文档信息
* 2: 配置生成规则
*/
/*Docket封装接口文档信息*/
@Bean // 标识该方法返回值作为一个Spring Bean加入到容器中。
public Docket getDocket(){
// 创建封面信息对象,这里设置了API文档的一些基本信息如标题、描述等。
ApiInfoBuilder apiInfoBuilder = new ApiInfoBuilder();
apiInfoBuilder.title("《商城》后端接口说明") // 文档标题
.description("此文档详细说明了商城项目后端接口规范....") // 文档描述
.version("v 2.0.1") // 文档版本号
.contact(new Contact("春哥", "www.dcc.com", "410816809@dcc.com")); // 联系人信息
ApiInfo apiInfo = apiInfoBuilder.build(); // 构建ApiInfo对象。
// 创建并配置Docket实例,它是Swagger的主要入口点,允许配置Swagger属性。
Docket docket = new Docket(DocumentationType.SWAGGER_2) // 指定Swagger版本为SWAGGER_2。
.apiInfo(apiInfo) // 设置上一步创建的ApiInfo对象,作为生成文档的封面信息。
.select() // 开始选择要包含在文档中的API。
.apis(RequestHandlerSelectors.basePackage("com.qfedu.fmmall.controller")) // 只包括来自指定基础包下的API。
.paths(PathSelectors.any()) // 包含所有路径。
.build(); // 完成Docket对象的构建。
return docket; // 返回配置好的Docket实例。
}
}
@Configuration
和@EnableSwagger2
注解用于声明这是一个配置类并且启用Swagger2。- 方法
getDocket()
被@Bean
注解标记,表示其返回的对象将被注册为Spring应用上下文中的一个bean。@Configuration
- 目的:这个注解用来标记一个类作为配置类,表明这个类可以用来定义Spring容器中的bean。
- 作用:被
@Configuration
注解的类会被Spring容器识别为一个配置源,里面可以包含一个或多个使用@Bean
注解的方法。这些方法将会被Spring容器调用以注册新的bean实例到Spring应用上下文中。这样做的好处是你可以通过编写Java代码的方式来配置你的Spring应用,而不是传统的XML配置文件。
@EnableSwagger2
- 目的:启用Swagger2的支持。
- 作用:
@EnableSwagger2
注解用于开启对Swagger2的支持,它会自动配置Spring MVC来暴露Swagger相关的端点(endpoints),使得我们可以自动生成RESTful API文档。这对于API的设计、测试以及维护非常有用,因为它允许开发者、测试人员甚至客户端查看API的详细信息,并直接在浏览器中测试API接口。
@Bean
- 目的:标识该方法返回值作为一个Spring Bean加入到容器中。
- 作用:当你在一个被
@Configuration
注解的类中使用@Bean
注解时,Spring容器会在启动时执行这个方法,并将它的返回值注册为一个Spring管理的bean。这意味着你可以通过Spring的依赖注入机制来使用这个bean。对于像Docket这样的对象来说,使用@Bean
注解可以让它成为Spring上下文的一部分,从而可以在其他地方被引用或者自动装配。
- 使用
ApiInfoBuilder
设置API文档的基本信息,如标题、描述、版本和联系信息。 Docket
实例通过.apiInfo(apiInfo)
方法与上述设定的文档信息关联,并通过.select()
方法开始选择哪些API应该被包含在文档中。.apis(RequestHandlerSelectors.basePackage(...))
指定了只包含来自特定包下的控制器的API。.paths(PathSelectors.any())
意味着选择所有的路径进行文档化。- 最后,通过
.build()
完成Docket对象的构建,并将其作为结果返回。
3.测试
启动SpringBoot应⽤,访问:http://localhost:8080/swagger-ui.html
4.遇到的一些问题
问题①:@RequestMapper注解中method参数导致接口文档生成的问题
package com.dcc.mall.controller;
import com.dcc.mall.service.UserService;
import com.dcc.mall.vo.ResultVO;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import javax.annotation.Resource;
/**
* @Author: 戴传春
* @Description: TODO
* @DateTime: 2025/3/18 6:53
**/
@Controller
@ResponseBody //返回给前端的都是JSON数据,因此这里直接在类上加@ResponseBody注解
@RequestMapping("/user")
public class UesrController {
@Resource
private UserService userService;
/**
* 接收前端发来的登录请求
*
* @param userName 用户名
* @param userPwd 密码
* @return
*/
@RequestMapping(value = "/login",method = RequestMethod.GET)
public ResultVO login(String userName, String userPwd) {
ResultVO resultVO = userService.checkLogin(userName, userPwd);
if (resultVO.getCode() == 10001) {
System.out.println("登入成功!");
return resultVO;
}
System.out.println("登入失败");
return null;
}
}
问题②:启动主类报org.springframework.context.ApplicationContextException: Failed to start bean 'documentationPluginsBootstrapper'; nested exception is java.lang.NullPointerException
错误
通常可能是Spring Boot 2.6及以上版本与Springfox Swagger的兼容性问题
步骤 1:在application.properties中添加路径匹配策略配置
- 在
src/main/resources/application.properties
文件中添加以下配置:
spring.mvc.pathmatch.matching-strategy=ant_path_matcher
解释:
spring.mvc.pathmatch.matching-strategy=ant_path_matcher
是 Spring Boot 中的一个配置选项,用于指定 URL 路径匹配的策略。它的作用是定义 Spring MVC 在处理请求时,如何将 HTTP 请求的 URL 路径与控制器(Controller)中定义的@RequestMapping
、@GetMapping
等注解中的路径模式进行匹配。
背景:两种路径匹配策略
在 Spring 5.3(对应 Spring Boot 2.6+)之后,Spring 提供了两种路径匹配策略:
ant_path_matcher
- 基于传统的 Ant 风格路径模式匹配(如
/api/**
匹配任意子路径)。 - 是 Spring Boot 2.5 及更早版本的默认策略。
- 语法示例:
?
:匹配单个字符。*
:匹配任意字符(不包含路径分隔符/
)。**
:匹配任意路径(包含路径分隔符/
)。
- 基于传统的 Ant 风格路径模式匹配(如
path_pattern_parser
- 基于新的 PathPattern 解析器,性能更高,但对路径匹配的规则更严格。
- 是 Spring Boot 2.6+ 的默认策略。
- 语法与
ant_path_matcher
类似,但在某些场景下行为不同(例如对 URI 编码路径的处理)。
为什么要配置
ant_path_matcher
?
当 Spring Boot 升级到 2.6 及以上版本时,默认使用 path_pattern_parser
。但某些旧版库(如 Springfox Swagger 2.9.2)可能尚未适配新的解析器,导致以下问题:
- 空指针异常(
NullPointerException
)。 - Swagger 生成的接口文档路径与实际控制器路径不匹配。
- 静态资源访问失败。
通过显式设置 spring.mvc.pathmatch.matching-strategy=ant_path_matcher
,可以强制 Spring MVC 使用旧的路径匹配策略,解决兼容性问题。
步骤 2:检查并调整Spring Boot或Swagger版本
如果上述配置无效,考虑以下三种方案之一:
方案①:关闭项目重新打开
方案②: 降级Spring Boot版本
在父pom.xml中将Spring Boot版本降至2.5.x或更低,例如:
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.5.14</version> <!-- 使用兼容的版本 -->
</parent>
方案③:升级到SpringDoc OpenAPI(推荐)
SpringDoc OpenAPI支持Spring Boot 2.6+,替换依赖
- 移除Springfox依赖:
<!-- 移除以下依赖 -->
<!--
<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>
-->
- 添加SpringDoc依赖:
<dependency>
<groupId>org.springdoc</groupId>
<artifactId>springdoc-openapi-ui</artifactId>
<version>1.6.14</version>
</dependency>
- 修改Swagger配置类:
import org.springdoc.core.GroupedOpenApi;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
public class SwaggerConfig {
@Bean
public GroupedOpenApi publicApi() {
return GroupedOpenApi.builder()
.group("mall")
.packagesToScan("com.dcc.mall.controller")
.build();
}
}
步骤 3:验证Controller包路径正确性
确保com.dcc.mall.controller
包存在且包含带有@RestController
或@Controller
注解的类。
步骤 4:确认依赖完整性
确保项目正确引入了spring-boot-starter-web
依赖。在api模块的pom.xml中添加(如果未传递):
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
完成以上步骤后,重新启动应用,访问Swagger UI:
- Springfox:
http://localhost:端口/swagger-ui.html
- SpringDoc:
http://localhost:端口/swagger-ui/index.html