context:component-scan

1.在spring配置文件中:

<!-- 使用Annotation自动注册Bean,解决事物失效问题:在主容器中不扫描@Controller注解,在SpringMvc中只扫描@Controller注解。  -->
	<context:component-scan base-package="com.thinkgem.jeesite"><!-- base-package 如果多个,用“,”分隔 -->
		<context:exclude-filter type="annotation" expression="org.springframework.stereotype.Controller"/>
	</context:component-scan>


2.在springmvc配置文件中:

<!-- 使用Annotation自动注册Bean,只扫描@Controller -->
	<context:component-scan base-package="com.thinkgem.jeesite"
		use-default-filters="false"><!-- base-package 如果多个,用“,”分隔 -->
		<context:include-filter type="annotation"
			expression="org.springframework.stereotype.Controller" />
	</context:component-scan>


说明:

use-default-filters属性,该属性默认为true,这就意味着会扫描指定包下的全部的标有@Component的类,并注册成bean.也就是@Component的子注解@Service,@Reposity等。

Use-dafault-filters=”false”的情况下:<context:exclude-filter>指定的不扫描,<context:include-filter>指定的扫描。

为什么不在spring中扫描controller:

Spring容器与SpringMVC容器是父子关系,子容器可以访问父容器的对象,父容器不能访问子容器的类,如果我们在springMVC配置文件中,直接扫描所有类,把service、dao、controller都交给SpringMVC去管理是可以的,但是假如用spring去管理Contoller,它是访问不到这个类的, 因为contoller是在springMVC容器中,假如在Spring配置直接扫描所有类包括controller,而不配置springMVC的话,这样服务器发来的请求,将会出现404的问题,因为它找不到controller,spring无法注入Controller。



为什么不直接在SpringMVC.xml中扫描所有类?

原则上我们是可以把service、dao 和controller都交给springMVC去管理,直接在SpringMVC配置文件中让它扫所有包就可以,但是出于未来扩展的考虑,spring和springMVC分开配置,由 spring 去管理service,有利于以后扩展,即便以后加多个struct2也不用影响原有配置

猜你喜欢

转载自maidong660.iteye.com/blog/2363671