`
lp895876294
  • 浏览: 280040 次
  • 性别: Icon_minigender_1
  • 来自: 济南
社区版块
存档分类
最新评论

SpringMVC容器和Spring容器冲突问题

    博客分类:
  • JAVA
 
阅读更多

       SpringMVC容器是Spring容器的一个子容器,它同样能够初始化实体类。由于SpringMVC容器的初始化是在Spring容器初始化之后,所以它会替换Spring中已经存在的类,这样可能会导致冲突。因此在Spring的配置文件中SpringMVC和Spring容器各司其职,在使用ComponentScan进行扫描时,各自扫描各自的实体类。如下配置:

spring容器扫描配置:

<context:component-scan base-package="com.projects.system">
		<context:exclude-filter type="annotation" expression="org.springframework.stereotype.Controller" />
	</context:component-scan>

SpringMVC容器扫描配置:

<context:component-scan base-package="com.projects.system">
    	<context:exclude-filter type="annotation" expression="org.springframework.stereotype.Service"/>
    	<context:exclude-filter type="annotation" expression="org.springframework.stereotype.Repository"/>
    </context:component-scan>

以上配置在使用Spring xml-based配置时是没有问题的。如果在项目中引入java-base配置时,同时引入了@Configuration注解,@Configuration注解是在Spring容器初始化时进行实体类的初始化工作,因此在SpringMVC扫描配置中要将其过滤掉,否则会导致SpringMVC 的rest地址不可访问的问题。新的配置如下:

<context:component-scan base-package="com.projects.system">
    	<context:exclude-filter type="annotation" expression="org.springframework.stereotype.Service"/>
    	<context:exclude-filter type="annotation" expression="org.springframework.stereotype.Repository"/>
    	<!-- 不扫描配置文件类,避免重复初始化 -->
    	<context:exclude-filter type="annotation" expression="org.springframework.context.annotation.Configuration"/>
    </context:component-scan>

 

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics