Spring3 MVC项目集成springfox-swagger2出现冲突报错如何解决
问题解答
1、Spring3 MVC是否无法使用springfox-swagger2?
Spring3 MVC 可以使用springfox-swagger2,但仅支持1.x系列的旧版本。你当前使用的2.9.2版本最低依赖Spring 4.x环境,和Spring 3.2.x版本不兼容,这也是你遇到Bean定义冲突报错的根本原因。
2、适配Spring3 MVC的Swagger实现方案
推荐使用适配Spring3的springfox 1.0.2版本,这是官方最后一个支持Spring3的springfox发行版,替换pom.xml中的Swagger依赖即可:
<!-- Swagger 适配Spring3版本 --> <dependency> <groupId>io.springfox</groupId> <artifactId>springfox-swagger2</artifactId> <version>1.0.2</version> </dependency> <dependency> <groupId>io.springfox</groupId> <artifactId>springfox-swagger-ui</artifactId> <version>1.0.2</version> </dependency>
如果不想使用springfox封装,也可以直接引入原生swagger-core 1.5.x系列依赖自行手动注册文档扫描逻辑,不过开发成本更高,优先推荐上述springfox低版本方案。
3、当前报错修复步骤
你遇到的同名Bean冲突是springfox 2.x和Spring3不兼容导致的,按以下步骤即可修复:
- 第一步:将pom.xml中的springfox-swagger2和springfox-swagger-ui依赖版本从2.9.2降级为1.0.2,删除原有2.9.2的依赖声明,替换为上述第二点给出的1.0.2版本依赖
- 第二步:调整Swagger配置类,适配1.x版本的API,配置示例如下:
import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import com.mangofactory.swagger.configuration.SpringSwaggerConfig; import com.mangofactory.swagger.models.dto.ApiInfo; import com.mangofactory.swagger.plugin.EnableSwagger; import com.mangofactory.swagger.plugin.SwaggerSpringMvcPlugin; @Configuration @EnableSwagger public class SwaggerConfig { @Bean public SwaggerSpringMvcPlugin customImplementation(SpringSwaggerConfig springSwaggerConfig) { return new SwaggerSpringMvcPlugin(springSwaggerConfig) .apiInfo(apiInfo()) .includePatterns(".*api.*"); // 配置要扫描的接口路径规则 } private ApiInfo apiInfo() { ApiInfo apiInfo = new ApiInfo( "项目接口文档", "接口文档描述", "1.0", "termsOfServiceUrl", "contact", "license", "licenseUrl" ); return apiInfo; } }
- 第三步:如果仍有Jackson序列化相关报错,可将Jackson依赖版本调整为2.6.7,适配Spring3的依赖规则:
<dependency> <groupId>com.fasterxml.jackson.core</groupId> <artifactId>jackson-annotations</artifactId> <version>2.6.7</version> </dependency> <dependency> <groupId>com.fasterxml.jackson.core</groupId> <artifactId>jackson-databind</artifactId> <version>2.6.7</version> </dependency>
- 第四步:启动项目后访问
http://{ip}:{port}/{项目上下文路径}/swagger-ui.html即可查看接口文档。
内容的提问来源于stack exchange,提问作者Hyun Jin
相关产品推荐
相关产品推荐

