Spring MVC 5.0.0.RELEASE加载swagger-ui.html报错及引用解析异常求助
解决Spring MVC 5中Swagger-ui加载时找不到/definitions/Error的问题
我之前也碰到过这个问题,其实根源就是Swagger在处理你自定义的全局响应消息时,找不到你指定的Error模型定义。下面给你几个具体的解决步骤:
1. 显式定义Error响应模型
Swagger需要明确的模型定义才能识别你在globalResponseMessage()中引用的Error类型。你可以创建一个带有@ApiModel注解的Error实体类:
import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; @ApiModel(description = "全局错误响应模型") public class Error { @ApiModelProperty(value = "错误码") private String errorCode; @ApiModelProperty(value = "错误描述") private String errorMessage; // 省略getter、setter和构造方法 }
2. 在Docket配置中添加该模型
如果你的Error类没有被Swagger自动扫描到(比如不是控制器的请求/响应参数),需要手动把它添加到Swagger的模型列表里。记得注入TypeResolver来解析这个类:
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.web.bind.annotation.RequestMethod; import springfox.documentation.builders.PathSelectors; import springfox.documentation.builders.RequestHandlerSelectors; import springfox.documentation.builders.ResponseMessageBuilder; import springfox.documentation.schema.ModelRef; import springfox.documentation.schema.TypeResolver; import springfox.documentation.service.ResponseMessage; import springfox.documentation.spi.DocumentationType; import springfox.documentation.spring.web.plugins.Docket; import springfox.documentation.swagger2.annotations.EnableSwagger2; import java.util.Arrays; @Configuration @EnableSwagger2 public class SwaggerConfig { @Autowired private TypeResolver typeResolver; @Bean public Docket api() { return new Docket(DocumentationType.SWAGGER_2) .select() .apis(RequestHandlerSelectors.any()) .paths(PathSelectors.any()) .build() // 关键:手动添加Error模型到Swagger文档中 .additionalModels(typeResolver.resolve(Error.class)) .globalResponseMessage(RequestMethod.GET, Arrays.asList( new ResponseMessageBuilder() .code(500) .message("服务器内部错误") // 这里的ModelRef名称要和Error类的@ApiModel名称一致(默认是类名) .responseModel(new ModelRef("Error")) .build() )); } }
3. 检查Springfox与Spring MVC的版本兼容性
Spring MVC 5.0需要搭配兼容的Springfox(Swagger的Spring实现)版本,建议使用2.9.2及以上的springfox-swagger2和springfox-swagger-ui,避免版本不兼容导致的模型解析问题。比如Maven依赖配置:
<dependency> <groupId>io.springfox</groupId> <artifactId>springfox-swagger2</artifactId> <version>2.9.2</version> </dependency> <dependency> <groupId>io.springfox</groupId> <artifactId>springfox-swagger-ui</artifactId> <version>2.9.2</version> </dependency>
4. 确认ModelRef名称与ApiModel一致
如果你给Error类的@ApiModel指定了value属性(比如@ApiModel(value = "CustomError")),那responseModel(new ModelRef("CustomError"))里的名称必须和这个value完全匹配,否则Swagger还是找不到对应的模型。
按照上面的步骤调整后,重新启动项目,swagger-ui.html应该就能正常加载,不会再出现找不到/definitions/Error的错误了。
内容的提问来源于stack exchange,提问作者Abdullah Al Mamun
相关产品推荐
相关产品推荐

