问题:我们使用swagger-version:2.10.5的时候,会出现问题,上下文重复,如图
网上说替换升级jar包,但是有的项目由于依赖的swagger版本整合很多,不方便升级jar包版本,同时升级了也会出现一系列问题。综合别人给出的意见,我们知道自动配置类SpringfoxWebConfiguration下pathProvider方法获取PathProvider导致的。然而获取这个对象也是由容器自动注入。所以如果我们能够替换掉这个bean的注入就可以解决我们的问题。
解决:
@Component
public class UbiPostProcesssor implements BeanPostProcessor {
@Value("${server.servlet.context-path}")
private String context;
@Override
public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
if("pathProvider".equals(beanName)){
return new DefaultPathProvider() {
@Override
public String getOperationPath(String operationPath) {
operationPath = operationPath.replaceFirst(context, "/");
UriComponentsBuilder uriComponentsBuilder = UriComponentsBuilder.fromPath("/");
return Paths.removeAdjacentForwardSlashes(uriComponentsBuilder.path(operationPath).build().toString());
}
@Override
public String getResourceListingPath(String groupName, String apiDeclaration) {
apiDeclaration = super.getResourceListingPath(groupName, apiDeclaration);
return apiDeclaration;
}
};
}
return BeanPostProcessor.super.postProcessBeforeInitialization(bean, beanName);
}
}
实现BeanPostProcessor接口,重写postProcessBeforeInitialization方法。通过阅读源码我们知道SpringfoxWebConfiguration在构建对象PathProvider时候的bean名字是pathProvider,所以指定名字,别的正常运行就可以。
方法二:我们知道spring框架加载注入是先根据类型,然后是名字去注入。所以可以采用.新增:
@Bean
@Primary
public PathProvider pathProvider2(){
return new DefaultPathProvider() {
@Override
public String getOperationPath(String operationPath) {
operationPath = operationPath.replaceFirst(context, "/");
UriComponentsBuilder uriComponentsBuilder = UriComponentsBuilder.fromPath("/");
return Paths.removeAdjacentForwardSlashes(uriComponentsBuilder.path(operationPath).build().toString());
}
@Override
public String getResourceListingPath(String groupName, String apiDeclaration) {
apiDeclaration = super.getResourceListingPath(groupName, apiDeclaration);
return apiDeclaration;
}
};
}