spring组件扫描<context:component-scan/>使用详解
<!-- 定义扫描根路径为leot.test,不使用默认的扫描方式 -->
<context:component-scan base-package="leot.test" use-default-filters="false">
<!-- 扫描符合@Service @Repository的类 -->
<context:include-filter type="annotation" expression="org.springframework.stereotype.Service" />
<context:include-filter type="annotation" expression="org.springframework.stereotype.Repository" />
< /context:component-scan> 下面是引用spring framework开发手册中的一段话“
Spring 2.5引入了更多典型化注解(stereotype annotations): @Component、@Service和@Controller。 @Component是所有受Spring管理组件的通用形式;而@Repository、@Service和@Controller则是@Component的细化,用来表示更具体的用例(例如,分别对应了持久化层、服务层和表现层)。也就是说,你能用@Component来注解你的组件类,但如果用@Repository、@Service 或@Controller来注解它们,你的类也许能更好地被工具处理,或与切面进行关联。例如,这些典型化注解可以成为理想的切入点目标。当然,在Spring Framework以后的版本中, @Repository、@Service和 @Controller也许还能携带更多语义。如此一来,如果你正在考虑服务层中是该用@Component还是@Service,那@Service显然是更好的选择。同样的,就像前面说的那样,@Repository已经能在持久化层中进行异常转换时被作为标记使用了。”
?
下面是网上目前关于组件扫描最详细的介绍
Spring applicationContext.xml的<context:component-scan>用途比我想像的要用。而且後才知道,有了<context:component-scan>,另一<context:annotation-config/>根本可以移除掉,因被包含去了。原本我survery Spring3通常只配置成<context:component-scan base-package="com.foo.bar"/>,意即在base-package下找有@Component和@Configuration的target Class。而在如下的粒:
<context:component-scan base-package="com.foo"use-default-filters="false">
<context:include-filter type="regex" expression="com.foo.bar.*Config"/>
< context:include-filter type="regex" expression="com.foo.config.*"/>
< /context:component-scan>
<context:component-scan>提供子:<context:include-filter>和<context:exclude-filter>各代表引入和排除的。而上例把use-default-filters性false,意即在base-package所有被宣告@Component和@Configuration等target Class不予bean,由filter子代。
filter在Spring3有五type,如下:
Filter TypeExamples ExpressionDescriptionannotationorg.example.SomeAnnotation符合SomeAnnoation的target classassignableorg.example.SomeClass指定class或interface的全名aspectjorg.example..*Service+AspectJ法regexorg\.example\.Default.*Regelar Expressioncustomorg.example.MyTypeFilterSpring3新增自Type,作org.springframework.core.type.TypeFilter所以上例用的regex就有病,com.foo.config.* 可以找到com.foo.config.WebLogger,但也可以找到com1fool2config3abcde,因小在Regex是任意字元,是故要用\.把小跳佳。(2010/3/15充:但要使用\.方式,其use-default-filters不能false,否抓不到,感是Bug)
Spring3提供富的Filter支援,有益配置策略,不需面Configuration Hell,比如Regex的com\.foo\.*\.action\.*Config,就可以找到com.foo package下所有action子package的*Config的target class。
?
转自:http://blog.csdn.net/ydwuli06/article/details/6993219