SpringBoot整合Swagger
1.添加依赖
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-boot-starter</artifactId>
<version>${springfox-swagger.version}</version>
</dependency>
注意:SpringBoot3暂时无法使用,应该是兼容性问题导致的。
2.添加配置
spring:
mvc:
pathmatch:
matching-strategy: ant_path_matcher
这里需要配置匹配策略,SpringMvc默认的策略是: PATH_PATTERN_PARSER,而使用Swagger的需要ANT_PATH_MATCHER。
简单地从源码中就可以找到:
public static class Pathmatch {
private MatchingStrategy matchingStrategy;
public Pathmatch() {
this.matchingStrategy = WebMvcProperties.MatchingStrategy.PATH_PATTERN_PARSER;
this.useSuffixPattern = false;
this.useRegisteredSuffixPattern = false;
}
}
public static enum MatchingStrategy {
ANT_PATH_MATCHER,
PATH_PATTERN_PARSER;
private MatchingStrategy() {
}
}
在yml文件中继续添加swagger相关的配置:
springfox:
documentation:
# 是否启用Swagger扫描代码生成文档
enabled: true
open-api:
# 是否启用Swagger的open-api
enabled: false
swagger-ui:
# 是否启用Swagger的Web UI
enabled: true
# 配置文档基础路径,此时路径为:/doc/swagger-ui/index.html
#base-url: /doc
3.添加自动配置
package com.zxyy.swagger.config;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.BeanPostProcessor;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.util.ReflectionUtils;
import org.springframework.web.servlet.mvc.method.RequestMappingInfoHandlerMapping;
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.spring.web.plugins.WebFluxRequestHandlerProvider;
import springfox.documentation.spring.web.plugins.WebMvcRequestHandlerProvider;
import springfox.documentation.swagger2.annotations.EnableSwagger2;
import java.lang.reflect.Field;
import java.util.List;
/**
* @Author lucky
* @Date 2023/12/21
* @Description Swagger配置类
**/
@Configuration
public class SwaggerConfig {
/**
* 文档
*/
@Bean
public Docket createRestApi() {
return new Docket(DocumentationType.SWAGGER_2)
.apiInfo(apiInfo())
.select()
.apis(RequestHandlerSelectors.basePackage("com.zxyy.swagger.controller"))
.paths(PathSelectors.any())
.build();
}
/**
* api相关的信息
*/
public ApiInfo apiInfo() {
return new ApiInfoBuilder()
.title("tiny-swagger")
.description("测试")
.contact(new Contact("lucky", null, null))
.version("1.0")
.build();
}
/**
* SpringBoot2.6.x以上的版本,需要添加这个Bean
*/
@Bean
public static BeanPostProcessor springfoxHandlerProviderBeanPostProcessor() {
return new BeanPostProcessor() {
@Override
public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
if (bean instanceof WebMvcRequestHandlerProvider | bean instanceof WebFluxRequestHandlerProvider) {
customizeSpringfoxHandlerMappings(getHandlerMappings(bean));
}
return bean;
}
private <T extends RequestMappingInfoHandlerMapping> void customizeSpringfoxHandlerMappings(List<T> mappings) {
List<T> copy = mappings.stream()
.filter(mapping -> mapping.getPatternParser() == null).toList();
mappings.clear();
mappings.addAll(copy);
}
@SuppressWarnings("unchecked")
public List<RequestMappingInfoHandlerMapping> getHandlerMappings(Object bean) {
try {
Field field = ReflectionUtils.findField(bean.getClass(), "handlerMappings");
field.setAccessible(true);
return (List<RequestMappingInfoHandlerMapping>) field.get(bean);
} catch (IllegalArgumentException | IllegalAccessException e) {
throw new IllegalStateException(e);
}
}
};
}
}
其实在这里遇到过一个问题,就是配置后一直无法显示接口,原因是我将图中的“==”写成了“!=”,导致我还以为是配置中的controller路径写错了,检查路径没问题后,debug才发现是这里的问题。还是需要更详细的了解SpringMVC的流程就更好了!
4.添加测试接口
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
/**
* @Author zhangxiang
* @Date 2023/12/21
* @Description
**/
@RestController
@Api(tags = "SwaggerController")
@Tag(name = "SwaggerController", description = "swagger测试")
@RequestMapping("/swagger/test")
public class SwaggerController {
@ApiOperation("查询所有的数据")
@GetMapping("/list")
public List<String> list() {
return new ArrayList<>(Arrays.asList("foo", "bar", "baz"));
}
}
这里做个简单的测试,下节将整合SpringSecurity,在存在安全验证的情况下,如何配置和使用Swagger。