一、Spring Boot 2.0 集成Swagger2异常
由于项目需要, 因此需要集成Swagger2到项目中, 按照官方文档进行配置后, 登录
http://localhost:8080/swagger-ui/index.html#/, 有错误提示如下:
二、项目依赖swagger版本
Springfox boot start依赖
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-boot-starter</artifactId>
<version>3.0.0</version>
</dependency>
三、swagger部分配置
@Configuration
@EnableSwagger2
public class Swagger2Configuration {
/**
* swagger
*/
@Bean
public Docket bpmnApi() {
return new Docket(DocumentationType.SWAGGER_2)
.apiInfo(apiInfo())
.select()
.apis(RequestHandlerSelectors.basePackage("com.bob"))
.paths(PathSelectors.any())
.build()
.pathMapping("/")
.useDefaultResponseMessages(false)
.globalRequestParameters(Collections.singletonList(
new RequestParameterBuilder()
.name("userId")
.description("userId")
.in(ParameterType.HEADER)
.required(false)
.query(q -> q.model(m -> m.scalarModel(ScalarType.LONG)))
.build())
);
}
private ApiInfo apiInfo() {
return new ApiInfoBuilder().build();
}
}
四、解决办法
经过排查后发现, 由于项目对返回体进行了自定义处理(@RestControllerAdvice), 因此会再次封装返回体, 导致Swagger无法读取到想要的参数,所以报错。解决办法在@RestControllerAdvice上指定要扫描的包basePackages,这样就不会对Swagger返回内容进行包装。