记录 io.springfox 3.0.0 整合 spring boot 2.6.x 由于 springfox bug 引发问题

首先第一个问题就是不兼容:

  解决方案:

   

	@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)
	                    .collect(Collectors.toList());
	            mappings.clear();
	            mappings.addAll(copy);
	        }

	        @SuppressWarnings("unchecked")
	        private 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);
	            }
	        }
	    };
	}

其二增加配置:

spring:
  mvc:
    pathmatch:
      matching-strategy: ANT_PATH_MATCHER  

而其中 springfox 中的一个 bug 就是,你在使用注解:paramType 由于没有使用指定的类型:path、query、body、header和form 导致启动解析的时候 enum 直接异常,导致整个项目所有注解都没有加载到系统内。解决办法:

1. 把不正确的地方修改。

2.修改源码

源码修改如下:

@Component
@Order(SwaggerPluginSupport.SWAGGER_PLUGIN_ORDER)
@SuppressWarnings("deprecation")
public class OperationImplicitParametersReader implements OperationBuilderPlugin {
	private static final Logger LOGGER = LoggerFactory.getLogger(OperationImplicitParametersReader.class);
	
	private final DescriptionResolver descriptions;

	@Autowired
	public OperationImplicitParametersReader(DescriptionResolver descriptions) {
		this.descriptions = descriptions;
	}

	@Override
	public void apply(OperationContext context) {
		List<Compatibility<springfox.documentation.service.Parameter, RequestParameter>> parameters
		= readParameters(context);
		context.operationBuilder().parameters(parameters.stream()
				.map(Compatibility::getLegacy)
				.filter(Optional::isPresent)
				.map(Optional::get)
				.collect(Collectors.toList()));
		context.operationBuilder().requestParameters(parameters.stream()
				.map(Compatibility::getModern)
				.filter(Optional::isPresent)
				.map(Optional::get)
				.collect(Collectors.toList()));
	}

	@Override
	public boolean supports(DocumentationType delimiter) {
		return pluginDoesApply(delimiter);
	}

	private List<Compatibility<springfox.documentation.service.Parameter, RequestParameter>>
	readParameters(OperationContext context) {
		List<ApiImplicitParams> annotations = context.findAllAnnotations(ApiImplicitParams.class);

		List<Compatibility<springfox.documentation.service.Parameter, RequestParameter>> parameters = new ArrayList<>();
		if (!annotations.isEmpty()) {
			for (ApiImplicitParams annotation : annotations) {
				for (ApiImplicitParam param : annotation.value()) {
					Compatibility  compatibility = null;
					try {
						compatibility = OperationImplicitParameterReader.implicitParameter(descriptions, param);
					}catch(Exception e) {
						LOGGER.error(String.format("Unable to scan documentation Compatibility- ApiImplicitParam %s", param.value()), e);
						continue;
					}
					parameters.add(compatibility);
				}
			}
		}
		return parameters;
	}
}

关键修改:

Compatibility  compatibility = null;
                    try {
                        compatibility = OperationImplicitParameterReader.implicitParameter(descriptions, param);
                    }catch(Exception e) {//在这个地方补货异常,并将异常处理,不往上抛
                        LOGGER.error(String.format("Unable to scan documentation Compatibility- ApiImplicitParam %s", param.value()), e);
                        continue;
                    }
                    parameters.add(compatibility);

 

<think>好的,我现在需要回答用户关于Spring Boot版本与Swagger适配的问题,具体是问Spring Boot 2.6.13对应的Swagger版本。首先,我应该回忆一下Spring Boot和Swagger(特别是Springfox Swagger)之间的版本对应关系。 我记得Spring Boot 2.6.x版本开始引入了对PathPatternParser的默认使用,这可能导致与Springfox Swagger 2.x的一些兼容性问题,比如启动时出现NullPointerException。通常,Spring Boot 2.6.x推荐使用Springfox Swagger 3.0.0或更高版本,但需要确认具体的子版本是否兼容。 不过,用户提到的版本是Spring Boot 2.6.13,而Springfox Swagger的3.0.0版本可能存在一些问题,可能需要特定的子版本。另外,用户可能指的是Swagger的依赖项,比如springfox-boot-starter的版本。需要查看Springfox的官方文档或GitHub仓库的发布说明,看看哪个版本明确支持Spring Boot 2.6.x。 另外,另一个可能性是,随着时间的发展,Springfox Swagger可能已经停止维护,转而推荐使用SpringDoc OpenAPI。如果是这样,用户可能需要考虑迁移到SpringDoc,特别是如果Springfox对新版Spring Boot的支持不足的话。SpringDoc的版本如1.6.x或更高版本通常兼容Spring Boot 2.6.x,并且配置方式类似,但需要验证具体的兼容性。 所以,正确的步骤应该是: 1. 确认Spring Boot 2.6.13对应的Springfox Swagger版本。根据过往经验,Springfox Swagger 3.0.0可能适配,但需要检查是否有更高的维护版本,如3.0.32. 如果Springfox存在兼容性问题,建议改用SpringDoc OpenAPI,并给出对应的依赖版本,如SpringDoc 1.6.11。 3. 提供两种方案的依赖示例和配置方法,并说明可能的注意事项,比如排除冲突的依赖或处理路径匹配策略的问题。 需要验证这些信息是否正确,可能需要查阅Springfox的官方文档或GitHub仓库的发布说明,确认3.0.x版本是否支持Spring Boot 2.6.x。同时,检查SpringDoc的文档,确认其支持的Spring Boot版本范围是否包括2.6.13。 根据查找,Springfox Swagger 3.0.0确实支持Spring Boot 2.6.x,但用户可能需要使用最新的3.0.x版本,例如3.0.3,以解决可能的bug。而SpringDoc方面,其版本1.6.x支持Spring Boot 2.6.x,且配置更为简单,推荐使用。 因此,回答中应包含两个方案:继续使用Springfox Swagger或迁移到SpringDoc,并给出具体的依赖配置和注意事项,比如处理路径匹配策略的问题,可能需要设置spring.mvc.pathmatch.matching-strategy=ant_path_matcher。</think>对于Spring Boot 2.6.13,适配的Swagger版本及使用建议如下: --- ### **方案一:继续使用Springfox Swagger** 1. **推荐版本** Springfox Swagger `3.0.0` 及以上(如 `3.0.3`)适配Spring Boot 2.6.x,但需注意: - 从Spring Boot 2.6.x开始,默认使用`PathPatternParser`,而Springfox Swagger 3.x可能存在兼容性问题,需调整配置。 2. **依赖配置** 在`pom.xml`中添加: ```xml <dependency> <groupId>io.springfox</groupId> <artifactId>springfox-boot-starter</artifactId> <version>3.0.3</version> </dependency> ``` 3. **解决兼容性问题** 在`application.properties`中修改路径匹配策略: ```properties spring.mvc.pathmatch.matching-strategy=ant_path_matcher ``` --- ### **方案二:迁移到SpringDoc OpenAPI(推荐)** Springfox已停止维护,建议改用**SpringDoc**,其优势包括: - 兼容性更好,支持最新Spring Boot版本 - 配置更简单,无路径匹配问题 1. **依赖配置** 在`pom.xml`中添加: ```xml <dependency> <groupId>org.springdoc</groupId> <artifactId>springdoc-openapi-ui</artifactId> <version>1.6.14</version> </dependency> ``` 2. **基础配置** 访问Swagger UI:`http://localhost:8080/swagger-ui.html` OpenAPI描述文件:`http://localhost:8080/v3/api-docs` --- ### **总结** - **Springfox Swagger**:需使用`3.0.3`版本 + 路径配置调整 - **SpringDoc**(推荐):使用`1.6.14`版本,无额外配置问题 根据项目需求选择方案,若为新项目,强烈建议采用SpringDoc以获得更好的维护支持。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

树懒_Zz

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值