Spring和SpringMVC搭配注解扫描的冲突

spring和springmvc搭配时注解扫描的冲突问题

因为两者是父子容器的关系,所以采用注解扫描的时候,应该区分不同层使用不同的扫描,一般spring扫描dao层和service层,而springmvc扫描controller层。


因此有两种解决办法:

法一:

在springMVC的配置文件中,只过滤其扫描controller层。

1
2
3
4
5

<contex:component-scan base-package="com.syz">
<contex:include-filter type="annotation" expression="org.springframework.stereotype.Controller" />
<contex:include-filter type="annotation" expression="org.springframework.web.bind.annotation.ControllerAdvice" />
</contex:component-scan>

法二:

在spring的配置文件中,排除扫描controller层

1
2
3
4
5
6
7
<context:component-scan base-package="com.syz">
<!--防止出现control无法拦截的情况,bean被多次加载-->
<context:exclude-filter type="annotation" expression="org.springframework.stereotype.Controller"/>
<context:exclude-filter type="annotation" expression="org.springframework.web.bind.annotation.RestController"/>

</context:component-scan>