網(wǎng)站首頁(yè) 編程語(yǔ)言 正文
spring-boot2.6.x兼容swagger2問(wèn)題
更改spring-boot2.6.x版本的默認(rèn)匹配策略
springfox 使用的是 ant_path_matcher 匹配策略
spring:
# ant_path_matcher、(spring-boot2.6.x默認(rèn)匹配策略)path-pattern-matcher
mvc:
pathmatch:
matching-strategy: ant_path_matcher
依賴
解決 io.swagger.models.parameters.AbstractSerializableParameter.getExample 的空指針異常,引入swagger-models依賴
<!--swagger2-->
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-boot-starter</artifactId>
<version>3.0.0</version>
</dependency>
<!-- 解決 io.swagger.models.parameters.AbstractSerializableParameter.getExample 的空指針異常 -->
<dependency>
<groupId>io.swagger</groupId>
<artifactId>swagger-models</artifactId>
<version>1.6.6</version>
</dependency>
<dependency>
<groupId>com.github.xiaoymin</groupId>
<artifactId>swagger-bootstrap-ui</artifactId>
<version>1.9.6</version>
</dependency>
SwaggerBeanPostProcessor 配置
package cn.springboot.model.base.config;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.BeanPostProcessor;
import org.springframework.stereotype.Component;
import org.springframework.util.ReflectionUtils;
import org.springframework.web.servlet.mvc.method.RequestMappingInfoHandlerMapping;
import springfox.documentation.spring.web.plugins.WebFluxRequestHandlerProvider;
import springfox.documentation.spring.web.plugins.WebMvcRequestHandlerProvider;
import java.lang.reflect.Field;
import java.util.List;
import java.util.stream.Collectors;
/**
* 兼容 springboot 2.6.x 處理
*
* @author jf
*/
@Component
public class SwaggerBeanPostProcessor implements 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)
.collect(Collectors.toList());
mappings.clear();
mappings.addAll(copy);
}
@SuppressWarnings("unchecked")
private List<RequestMappingInfoHandlerMapping> getHandlerMappings(Object bean) {
try {
Field field = ReflectionUtils.findField(bean.getClass(), "handlerMappings");
assert field != null;
field.setAccessible(true);
return (List<RequestMappingInfoHandlerMapping>) field.get(bean);
} catch (IllegalArgumentException | IllegalAccessException e) {
throw new IllegalStateException(e);
}
}
}
SwaggerConfig 配置
package cn.springboot.model.base.config;
import io.swagger.models.auth.In;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.util.ResourceUtils;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
import springfox.documentation.builders.ApiInfoBuilder;
import springfox.documentation.builders.PathSelectors;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.service.*;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spi.service.contexts.SecurityContext;
import springfox.documentation.spring.web.plugins.Docket;
import java.util.ArrayList;
import java.util.List;
/**
* Swagger2 的接口配置
*
* @author jf
*/
@Configuration
public class SwaggerConfig { //implements WebMvcConfigurer {
/**
* 系統(tǒng)基礎(chǔ)配置
*/
@Autowired
private ModelConfig modelConfig;
/**
* 是否開(kāi)啟swagger
*/
@Value("${swagger.enabled}")
private boolean enabled;
/**
* 設(shè)置請(qǐng)求的統(tǒng)一前綴
*/
@Value("${swagger.pathMapping}")
private String pathMapping;
/**
* 分組:sys管理
*
* @return Docket
*/
@Bean
public Docket sys_api_app() {
return new Docket(DocumentationType.SWAGGER_2)
// 是否啟用Swagger
.enable(enabled)
.apiInfo(apiInfo("標(biāo)題:學(xué)生管理_API", "學(xué)生"))
.select()
.apis(RequestHandlerSelectors.basePackage("cn.springboot.model.web.controller"))
// .apis(RequestHandlerSelectors.withMethodAnnotation(ApiOperation.class))
// .apis(RequestHandlerSelectors.any())
// .paths(PathSelectors.any())
.paths(PathSelectors.ant("/stu/**"))
.build()
.groupName("學(xué)生")
.securitySchemes(securitySchemes())
.securityContexts(securityContexts())
.pathMapping(pathMapping);
}
@Bean
public Docket clas_api_app() {
return new Docket(DocumentationType.SWAGGER_2)
// 是否啟用Swagger
.enable(enabled)
.apiInfo(apiInfo("標(biāo)題:班級(jí)管理_API", "班級(jí)"))
.select()
.apis(RequestHandlerSelectors.basePackage("cn.springboot.model.web.controller"))
// .apis(RequestHandlerSelectors.withMethodAnnotation(ApiOperation.class))
// .apis(RequestHandlerSelectors.any())
// .paths(PathSelectors.any())
.paths(PathSelectors.ant("/class/**"))
.build()
.groupName("班級(jí)")
.securitySchemes(securitySchemes())
.securityContexts(securityContexts())
.pathMapping(pathMapping);
}
/**
* 安全模式,這里指定token通過(guò)Authorization頭請(qǐng)求頭傳遞
*/
private List<SecurityScheme> securitySchemes() {
List<SecurityScheme> apiKeyList = new ArrayList<SecurityScheme>();
apiKeyList.add(new ApiKey("Authorization", "Authorization", In.HEADER.toValue()));
return apiKeyList;
}
/**
* 安全上下文
*/
private List<SecurityContext> securityContexts() {
List<SecurityContext> securityContexts = new ArrayList<>();
securityContexts.add(
SecurityContext.builder()
.securityReferences(defaultAuth())
// .forPaths(o -> o.matches("/.*"))
.build());
return securityContexts;
}
/**
* 默認(rèn)的安全上引用
*/
private List<SecurityReference> defaultAuth() {
AuthorizationScope authorizationScope = new AuthorizationScope("global", "accessEverything");
AuthorizationScope[] authorizationScopes = new AuthorizationScope[1];
authorizationScopes[0] = authorizationScope;
List<SecurityReference> securityReferences = new ArrayList<>();
securityReferences.add(new SecurityReference("Authorization", authorizationScopes));
return securityReferences;
}
/**
* 構(gòu)建api文檔的詳細(xì)信息
*
* @param title 標(biāo)題
* @param description 描述
* @return ApiInfo
*/
private ApiInfo apiInfo(String title, String description) {
return new ApiInfoBuilder()
.title(title)
.description(description)
// 作者信息
.contact(new Contact(modelConfig.getName(), null, null))
.version("版本號(hào):" + modelConfig.getVersion())
.build();
}
// @Override
// public void addResourceHandlers(ResourceHandlerRegistry registry) {
// registry.addResourceHandler("swagger-ui.html")
// .addResourceLocations("classpath:/META-INF/resources/");
// registry.addResourceHandler("/webjars/**")
// .addResourceLocations("classpath:/META-INF/resources/webjars/");
// registry.addResourceHandler("/static/**")
// .addResourceLocations(ResourceUtils.CLASSPATH_URL_PREFIX + "/static/");
// WebMvcConfigurer.super.addResourceHandlers(registry);
// }
}
原文鏈接:https://blog.csdn.net/qq_42476834/article/details/125534198
相關(guān)推薦
- 2022-12-28 React組件實(shí)例三大核心屬性State?props?Refs詳解_React
- 2022-06-30 go-micro集成RabbitMQ實(shí)戰(zhàn)和原理詳解_Golang
- 2022-03-31 python猜單詞游戲的實(shí)現(xiàn)_python
- 2023-01-21 Python參數(shù)解析器configparser簡(jiǎn)介_(kāi)python
- 2022-08-04 react使用mobx封裝管理用戶登錄的store示例詳解_React
- 2022-07-18 springboot解決Invalid character found in the request
- 2022-12-07 C++成員函數(shù)后面加override問(wèn)題_C 語(yǔ)言
- 2022-03-20 Entity?Framework?Core關(guān)聯(lián)刪除_實(shí)用技巧
- 最近更新
-
- window11 系統(tǒng)安裝 yarn
- 超詳細(xì)win安裝深度學(xué)習(xí)環(huán)境2025年最新版(
- Linux 中運(yùn)行的top命令 怎么退出?
- MySQL 中decimal 的用法? 存儲(chǔ)小
- get 、set 、toString 方法的使
- @Resource和 @Autowired注解
- Java基礎(chǔ)操作-- 運(yùn)算符,流程控制 Flo
- 1. Int 和Integer 的區(qū)別,Jav
- spring @retryable不生效的一種
- Spring Security之認(rèn)證信息的處理
- Spring Security之認(rèn)證過(guò)濾器
- Spring Security概述快速入門(mén)
- Spring Security之配置體系
- 【SpringBoot】SpringCache
- Spring Security之基于方法配置權(quán)
- redisson分布式鎖中waittime的設(shè)
- maven:解決release錯(cuò)誤:Artif
- restTemplate使用總結(jié)
- Spring Security之安全異常處理
- MybatisPlus優(yōu)雅實(shí)現(xiàn)加密?
- Spring ioc容器與Bean的生命周期。
- 【探索SpringCloud】服務(wù)發(fā)現(xiàn)-Nac
- Spring Security之基于HttpR
- Redis 底層數(shù)據(jù)結(jié)構(gòu)-簡(jiǎn)單動(dòng)態(tài)字符串(SD
- arthas操作spring被代理目標(biāo)對(duì)象命令
- Spring中的單例模式應(yīng)用詳解
- 聊聊消息隊(duì)列,發(fā)送消息的4種方式
- bootspring第三方資源配置管理
- GIT同步修改后的遠(yuǎn)程分支