Swagger 与 spring mvc 集成

最近研究swagger,网上也搜了不少与springmvc 集成的方式,但是发现最终都有问题。

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

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

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

整合过spring 与 spring mvc的童鞋应该都知道,spring容器与springmvc的容器其实是两个容器,既父容器和子容器,如果在他们两个集成时,没有指定扫描注解,那么spring管理的bean会被创建两次。通常我们集成的时候是这样配置的:

<!-- 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>

通过上面配置不知道大家有没有明白?问题出在哪里?

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

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

<!-- 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了。

转载于:https://my.oschina.net/lis1314/blog/801927

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值