Swagger 与 spring mvc 集成

最近研究swagger,网上也搜了很多与springmvc 集成的方式,可是发现最终都有问题。php

好比:http://javatech.wang/index.php/archives/74/,这篇文章写的已经很详细了。java

可是按照文章上的作,可能还会出现注入失败的问题,其实缘由并再也不集成里面,而是和你的项目环境有关。web

我整合的时候也发生了注入失败的问题,后来看了SpringSwaggerConfig类的源码,发现它依赖了一些其余的类,实际上它依赖的这些类有一些是在spring mvc的容器中的(不知道这里你们有没有看明白)spring

整合过spring 与 spring mvc的童鞋应该都知道,spring容器与springmvc的容器实际上是两个容器,既父容器和子容器,若是在他们两个集成时,没有指定扫描注解,那么spring管理的bean会被建立两次。一般咱们集成的时候是这样配置的:express

<!-- SpringMvc配置文件,只扫描Controller和ControllerAdvice标记的注解 -->
<context:component-scan base-package="com.xxx.**.controller" use-default-filters="false">
	<context:include-filter type="annotation"
			expression="org.springframework.stereotype.Controller" />
	<context:include-filter type="annotation"
			expression="org.springframework.web.bind.annotation.ControllerAdvice" />
</context:component-scan>
<!-- Spring配置文件,排除Controller和ControllerAdvice标记的注解,扫描其余任何注解 -->
<context:component-scan base-package="com.xxx">
	<context:exclude-filter type="annotation"
			expression="org.springframework.stereotype.Controller" />
	<context:exclude-filter type="annotation"
			expression="org.springframework.web.bind.annotation.ControllerAdvice" />
</context:component-scan>

经过上面配置不知道你们有没有明白?问题出在哪里?mvc

在看SpringSwaggerConfig源码,它里面实际上依赖了springmvc 子容器的类,想象一下,假设咱们写的代码里,service层依赖controller层能注入进去么?这个就比如是这种状况。由于SpringSwaggerConfig它是由spring容器管理的,而不是spring mvc的容器,因此在spring容器建立它的过程当中,有一些类其实是在springmvc子容器中的。好了不在啰嗦了。code

最终解决方案(修改spring的配置文件,不让他管理SpringSwaggerConfig)component

<!-- Spring配置文件,排除Controller,ControllerAdvice,EnableSwagger标记的注解,扫描其余任何注解 -->
<context:component-scan base-package="com.xxx">
	<context:exclude-filter type="annotation"
		expression="org.springframework.stereotype.Controller" />
	<context:exclude-filter type="annotation"
		expression="org.springframework.web.bind.annotation.ControllerAdvice" />
	<context:exclude-filter type="annotation"
	expression="com.mangofactory.swagger.plugin.EnableSwagger" />
</context:component-scan>

 

我想你们应该看的很明白了。为何发生这种问题,让spring容器排除EnableSwagger注解就OK了。xml

相关文章
相关标签/搜索