最近研究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