对比项 | SWAGGER2 | SWAGGER3 |
---|---|---|
注解配置 | EnableSwagger2 | @EnableOpenApi |
相关依赖 | springfox-swagger2 springfox-swagger-ui | springfox-boot-starter |
访问地址 | http://localhost:8080/swagger-ui.html | http://localhost:8080/swagger-ui/index.html |
文档摘要 | SWAGGER_2 | OAS_3 |
方法描述 | @ApiOperation(value = “控制器的方法描述”) | @Operation(summary = “控制器的方法描述”) |
参数描述 | @ApiParam(name = “控制器方法的参数描述”) | @Parameter(description = “控制器方法的参数描述”) |
Spring Cloud gateway 在集成SWAGGER容易出现该问题,主要从GATEWAY的访问权限入手进行排查。
A. 务必务必务必核实POM.XML中的依赖,大部分由于缺少相关依赖造成的。
B. 请求被拦截
// SWAGGER3
@Configuration
public class SwaggerWebConfiguration implements WebMvcConfigurer {
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
/** swagger-ui 地址 */
registry.addResourceHandler("/swagger-ui/**")
.addResourceLocations("classpath:/META-INF/resources/webjars/springfox-swagger-ui/");
}
}
// SWAGGER2
@Configuration
public class SwaggerWebConfiguration implements WebMvcConfigurer {
@Override
protected void addResourceHandlers(ResourceHandlerRegistry registry) {
// 解决静态资源无法访问
registry.addResourceHandler("/**")
.addResourceLocations("classpath:/static/");
// 解决SWAGGER无法访问
registry.addResourceHandler("/swagger-ui.html")
.addResourceLocations("classpath:/META-INF/resources/");
// 解决SWAGGER的JS文件无法访问
registry.addResourceHandler("/webjars/**")
.addResourceLocations("classpath:/META-INF/resources/webjars/");
}
}
@Bean
public Docket api(SwaggerProperties swaggerProperties) {
...
ApiSelectorBuilder builder = new Docket(DocumentationType.OAS_30)
.host(swaggerProperties.getHost())
.apiInfo(apiInfo(swaggerProperties))
.select()
.apis(RequestHandlerSelectors.basePackage(swaggerProperties.getBasePackage()));
swaggerProperties.getBasePath().forEach(p -> builder.paths(PathSelectors.ant(p)));
swaggerProperties.getExcludePath().forEach(p -> builder.paths(PathSelectors.ant(p).negate()));
return builder.build().globalRequestParameters(getGlobalOperationParameters()).pathMapping("/");
}
// 在HEADER中添加公共参数
private List<RequestParameter> getGlobalOperationParameters() {
List<RequestParameter> parameters = Arrays.asList(
new RequestParameterBuilder().name("token").description("令牌").in(ParameterType.HEADER).query(q -> q.model(m -> m.scalarModel(ScalarType.STRING))).build(),
new RequestParameterBuilder().name("requestId").description("请求ID").in(ParameterType.HEADER).query(q -> q.model(m -> m.scalarModel(ScalarType.STRING))).build(),
new RequestParameterBuilder().name("Content-Type").description("内容类型").in(ParameterType.HEADER).query(q -> q.model(m -> m.scalarModel(ScalarType.STRING)).defaultValue("application/json")).build()
);
return parameters;
}
@Profile({"dev", "test"}) // 只有开发和测试环境下SWAGGER才会开启
public class SwaggerAutoConfiguration {
...
}